In this question:
Print template typename at compile time
we have a few suggestions regarding how to get typical C++ compilers to print a type's name, at compile time. However, they rely on triggering a compilation error.
My question: Can I get the C++ compiler to print the name of a type without stopping compilation?
I'm asking specifically about GCC and clang, with possible use of preprocessor directives, compiler builtins, or any compiler-specific trick.
Notes:
using/typedef
statements, template parameter values, variadic templates etc. If the type is available explicitly you could just use something like #message "my type is unsigned long long"
(as @NutCracker suggested). But that's not what the question is about.The following mechanism is due to @JonathanWakely, and is specific to GCC:
int i;
template <typename T>
[[gnu::warning("type printed for your convenience")]]
bool your_type_was_() { return true; }
#define print_type_of(_x) your_type_was_<decltype(_x)>()
bool b = print_type_of(i);
This gives you:
<source>: In function 'void __static_initialization_and_destruction_0(int, int)':
<source>:7:55: warning: call to 'your_type_was_<int>' declared with attribute warning: type printed for your convenience [-Wattribute-warning]
7 | #define print_type_of(_x) your_type_was_<decltype(_x)>()
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
<source>:9:10: note: in expansion of macro 'print_type_of'
9 | bool b = print_type_of(i);
| ^~~~~~~~~~~~~
See it working on Godbolt.