C++ Get name of type in template

后端 未结 10 2052
天涯浪人
天涯浪人 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<typename T>
    struct TypeParseTraits
    { static const char* name; };
    
    // in c-file
    #define REGISTER_PARSE_TYPE(X) \
        template <> const char* TypeParseTraits<X>::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...

    0 讨论(0)
  • 2020-11-27 12:17

    As mentioned by Bunkar typeid(T).name is implementation defined.

    To avoid this issue you can use Boost.TypeIndex library.

    For example:

    boost::typeindex::type_id<T>().pretty_name() // human readable
    
    0 讨论(0)
  • 2020-11-27 12:18

    I just leave it there. If someone will still need it, then you can use this:

    template <class T>
    bool isString(T* t) { return false;  } // normal case returns false
    
    template <>
    bool isString(char* t) { return true; }  // but for char* or String.c_str() returns true
    .
    .
    .
    

    This will only CHECK type not GET it and only for 1 type or 2.

    0 讨论(0)
  • 2020-11-27 12:21

    As a rephrasing of Andrey's answer:

    The Boost TypeIndex library can be used to print names of types.

    Inside a template, this might read as follows

    #include <boost/type_index.hpp>
    #include <iostream>
    
    template<typename T>
    void printNameOfType() {
        std::cout << "Type of T: " 
                  << boost::typeindex::type_id<T>().pretty_name() 
                  << std::endl;
    }
    
    0 讨论(0)
提交回复
热议问题