Question

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.

Was it helpful?

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.

OTHER TIPS

The really easy solution: Just pass a string object to the constructor of SomeClass that says what the type is.

Example:

#define TO_STRING(type) #type
SomeClass<int> s(TO_STRING(int));

Simply store it and display it in the implementation of GetClassName.

Slightly more complicated solution, but still pretty easy:

#define DEC_SOMECLASS(T, name) SomeClass<T> name;  name.sType = #T; 

template< typename T >
struct SomeClass
{
    const char* GetClassName() const { return sType.c_str(); }
    std::string sType;
};


int main(int argc, char **argv)
{
    DEC_SOMECLASS(int, s);
    const char *p = s.GetClassName();

    return 0;
}

Template non type solution:

You could also make your own type ids and have a function to convert to and from the ID and the string representation.

Then you can pass the ID when you declare the type as a template non-type parameter:

template< typename T, int TYPEID>
struct SomeClass
{
    const char* GetClassName() const { return GetTypeIDString(TYPEID); }
};


...

SomeClass<std::string, STRING_ID> s1;
SomeClass<int, INT_ID> s2;

You can try something like this (warning this is just off the top of my head, so there may be compile errors, etc..)

template <typename T>
const char* GetTypeName()
{
    STATIC_ASSERT(0); // Not implemented for this type
}

#define STR(x) #x
#define GETTYPENAME(x) str(x) template <> const char* GetTypeName<x>() { return STR(x); }

// Add more as needed
GETTYPENAME(int)
GETTYPENAME(char)
GETTYPENAME(someclass)

template< typename T >
struct SomeClass
{
    const char* GetClassName() const { return GetTypeName<T>; }
}

This will work for any type that you add a GETTYPENAME(type) line for. It has the advantage that it works without modifying the types you are interested in, and will work with built-in and pointer types. It does have the distinct disadvantage that you must a line for every type you want to use.

Without using the built-in RTTI, you're going to have to add the information yourself somewhere, either Brian R. Bondy's answer or dirkgently's will work. Along with my answer, you have three different locations to add that information:

  1. At object creation time using SomeClass<int>("int")
  2. In the class using dirkgently's compile-time RTTI or virtual functions
  3. With the template using my solution.

All three will work, it's just a matter of where you'll end up with the least maintenance headaches in your situation.

By you don't have access to RTTI, does that mean you can't use typeid(T).name()? Because that's pretty much the only way to do it with the compiler's help.

Is it very important for the types to have unique names, or are the names going to be persisted somehow? If so, you should consider giving them something more robust than just the name of the class as declared in the code. You can give two classes the same unqualified name by putting them in different namespaces. You can also put two classes with the same name (including namespace qualification) in two different DLLs on Windows, so you need the identify of the DLL to be included in the name as well.

It all depends on what you're going to do with the strings, of course.

You can add a little magic yourself. Something like:

#include <iostream>

#define str(x) #x
#define xstr(x) str(x)
#define make_pre(C) concat(C, <)
#define make_post(t) concat(t, >)

#define make_type(C, T) make_pre(C) ## make_post(T)
#define CTTI_REFLECTION(T, x)  static std::string my_typeid() \
                               { return xstr(make_type(T, x)); }


// the dark magic of Compile Time Type Information (TM)
#define CTTI_REFLECTION(x)  static const char * my_typeid() \
                                  { return xstr(make_type(T, x)); }

#define CREATE_TEMPLATE(class_name, type) template<> \
                                    struct class_name <type>{ \
                                        CTTI_REFLECTION(class_name, type) \
                                    }; 

// dummy, we'll specialize from this later
template<typename T> struct test_reflection;

// create an actual class
CREATE_TEMPLATE(test_reflection, int)

struct test_reflection {
  CTTI_REFLECTION(test_reflection)
};

int main(int argc, char* argv[])
{
    std::cout << test_reflection<int>::my_typeid();
}

I'll make the inspector a static function (and hence non-const).

No, sorry.

And RTTI won't even compile if you try to use it on int.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top