Search code examples
c++stringtemplatestypeid

Is it possible to get a char* name from a template type in C++


I want to get the string name (const char*) of a template type. Unfortunately I don't have access to RTTI.

template< typename T >
struct SomeClass
{
    const char* GetClassName() const { return /* magic goes here */; }
}

So

SomeClass<int> sc;
sc.GetClassName();   // returns "int"

Is this possible? I can't find a way and am about to give up. Thanks for the help.


Solution

  • No and it will not work reliable with typeid either. It will give you some internal string that depends on the compiler implementation. Something like "int", but also "i" is common for int.

    By the way, if what you want is to only compare whether two types are the same, you don't need to convert them to a string first. You can just do

    template<typename A, typename B>
    struct is_same { enum { value = false }; };
    
    template<typename A>
    struct is_same<A, A> { enum { value = true }; };
    

    And then do

    if(is_same<T, U>::value) { ... }
    

    Boost already has such a template, and the next C++ Standard will have std::is_same too.

    Manual registration of types

    You can specialize on the types like this:

    template<typename> 
    struct to_string {
        // optionally, add other information, like the size
        // of the string.
        static char const* value() { return "unknown"; }
    };
    
    #define DEF_TYPE(X) \
        template<> struct to_string<X> { \
            static char const* value() { return #X; } \
        }
    
    DEF_TYPE(int); DEF_TYPE(bool); DEF_TYPE(char); ...
    

    So, you can use it like

    char const *s = to_string<T>::value();
    

    Of course, you can also get rid of the primary template definition (and keep only the forward declaration) if you want to get a compile time error if the type is not known. I just included it here for completion.

    I used static data-members of char const* previously, but they cause some intricate problems, like questions where to put declarations of them, and so on. Class specializations like above solve the issue easily.

    Automatic, depending on GCC

    Another approach is to rely on compiler internals. In GCC, the following gives me reasonable results:

    template<typename T>
    std::string print_T() {
        return __PRETTY_FUNCTION__;
    }
    

    Returning for std::string.

    std::string print_T() [with T = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]

    Some substr magic intermixed with find will give you the string representation you look for.