C++ Get name of type in template

后端 未结 10 2149
天涯浪人
天涯浪人 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:06

    Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like:

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

    And then use it like

    throw ParseError(TypeParseTraits::name);
    

    EDIT:

    You could also combine the two, change name to be a function that by default calls typeid(T).name() and then only specialize for those cases where that's not acceptable.

提交回复
热议问题