C++ Get name of type in template

后端 未结 10 2147
天涯浪人
天涯浪人 2020-11-27 11:28

I\'m writing some template classes for parseing some text data files, and as such it is likly the great majority of parse errors will be due to errors in the data file, whic

10条回答
  •  野性不改
    2020-11-27 12:10

    The answer of Logan Capaldo is correct but can be marginally simplified because it is unnecessary to specialize the class every time. One can write:

    // in header
    template
    struct TypeParseTraits
    { static const char* name; };
    
    // in c-file
    #define REGISTER_PARSE_TYPE(X) \
        template <> const char* TypeParseTraits::name = #X
    
    REGISTER_PARSE_TYPE(int);
    REGISTER_PARSE_TYPE(double);
    REGISTER_PARSE_TYPE(FooClass);
    // etc...
    

    This also allows you to put the REGISTER_PARSE_TYPE instructions in a C++ file...

提交回复
热议问题