Stringifying template arguments

前端 未结 8 1663
花落未央
花落未央 2020-12-04 17:00

Is it possible in C++ to stringify template arguments? I tried this:

#define STRINGIFY(x) #x

template 
struct Stringify
{
     Stringify()         


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 17:20

    No, you cannot work on types as if they were variables. You could write code that extracted the typeid() of an element and printed the name, but the resulting value will probably not be what you expect (type names are not standarized).

    You can also work with template specializations (and some macro magic) to achieve a more interesting version if the number of types you want to work with is limited:

    template  const char* printtype(); // not implemented
    
    // implement specializations for given types
    #define DEFINE_PRINT_TYPE( type ) \
    template<>\
    const char* printtype() {\
       return #type;\
    }
    DEFINE_PRINT_TYPE( int );
    DEFINE_PRINT_TYPE( double );
    // ... and so on
    #undef DEFINE_PRINT_TYPE
    template  void test()
    {
       std::cout << printtype() << std::endl;
    }
    int main() {
       test();
       test();
       test(); // compilation error, printtype undefined for float
    }
    

    Or you could even combine both versions: implement the printtype generic template using typeinfo and then provide specializations for the types you want to have fancier names.

    template 
    const char* printtype()
    {
       return typeid(T).name();
    }
    

提交回复
热议问题