c++g++clang++compile-timedebug-print

Print a type's name at compile time without aborting compilation?


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?

In general the answer is "probably not", because a valid program can be compiled into its target object without printing anything anywhere, so I'm asking specifically about GCC and clang, with possible use of preprocessor directives, compiler builtins, or any compiler-specific trick.

Notes:


Solution

  • 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.