views:

716

answers:

8

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.

A: 

No, sorry.

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

Joshua
typeid(int) does work.
MSN
It didn't when I learned C++. <g>
Joshua
one doesn'T know. as far as i know, there is no "hosted c++ implementation without RTTI" option available by the standard. so one has to guess or not say something at all about it :)
Johannes Schaub - litb
+1  A: 

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.

MSN
Pretty sure typeid only comes if RTTI is on, so no typeid.
Rosco
Strictly speaking RTTI also includes dynamic_cast, and if this is MSVC being compiled with /GR, you still can use typeid, you just can't use it on a variable and expect the right result. You can go happy with a type though.
MSN
A: 

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).

dirkgently
+3  A: 

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;
Brian R. Bondy
that's unfortunately not posible. you can't pass string literals to templates
Johannes Schaub - litb
ya i figured that out i'm writing a new solution now :)
Brian R. Bondy
ok posted corrected info
Brian R. Bondy
DEC_SOMECLASS is actually a definition of an object :)
dirkgently
ya it's short for declare an object of the SomeClass class.
Brian R. Bondy
I don't want to add instance data to the class, since it is representing data off disk, static data is fine. Also the solution needs to be done at declaration time. I'm declaring classes in other classes that I need to get the text name from the templated type. Sorry I wasn't more specific.
Rosco
I added a third solution that might work for you
Brian R. Bondy
+2  A: 

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.

Eclipse
+4  A: 

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.

Johannes Schaub - litb
Not doing type equality. I tried the compiler specific approach, but I'm using MS (equivalent doesn't work). The 2nd approach is nice, non-intrusive. I have some other macros being used, so this could work easily. Also I can make a compile time assert if you haven't defined the type you are using.
Rosco
Would __FUNCTION__ help for MS compilers? (I don't have one to test on.) Ref: http://stackoverflow.com/questions/597078/file-line-and-function-usage-in-c/598031
Mr.Ree
mrree, i'm sorry i have not tested how __FUNCTION__ looks like. if it prints just the name of the function, we are lost. if it prints the template parameters it got too, we are not :) best test it and please report back your result. thanks :)
Johannes Schaub - litb
A: 

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.

Daniel Earwicker
A: 

I've tried the following in Visual C++ - but the input ident when debugging in RegisterElement below is always "T" which is just plain wrong ... :(

bool RegisterElement(const char* ident, Element::Constructor constructor);

template <class T> Element* Allocate() { return new T; }

#define TYPE_TO_STRING(type) #type

    template <class T> bool Register(const char* ident) 
    {
        return RegisterElement(TYPE_TO_STRING(T), Allocate<T>);
    }
rasmuskaae