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.
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
And then do
Boost already has such a template, and the next C++ Standard will have
std::is_sametoo.Manual registration of types
You can specialize on the types like this:
So, you can use it like
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:
Returning for
std::string.Some
substrmagic intermixed withfindwill give you the string representation you look for.