c++reflection

Compile time typeid without RTTI with GCC


Is there anyway to get compile-time typeid information from GCC with RTTI disabled? Under Visual Studio, a simple command like const char* typeName = typeid(int).name(); will appropriately return "int", even if RTTI is disabled. Unfortunately, GCC can't do the same. When I try to call typeid without RTTI, my program crashes. I know disabling RTTI is not part of the standard, but is there anyway I can force GCC to do compile time resolution of known types?

RTTI is disabled for performance reasons. I have no need for runtime RTTI.

Edit:

Here's what I ended up going with:

template<typename T> const char* TypeName(void);
template<typename T> const char* TypeName(T type) { return TypeName<T>(); }

#define REFLECTION_REGISTER_TYPE(type) \
    template <> const char* TypeName<type>(void) { return #type; } 

It requires that REFLECTION_REGISTER_TYPE be called for every type that needs reflection info. But as long as it's called for every required type, calling TypeName<int> works perfectly. I also added the function TypeName(T type) which means you can do things like this: int x = 0; printf(TypeName(x)); and it will print out "int". GCC should really be able to do this at compile time like VC++ can.


Solution

  • No. RTTI is RunTime Type Information (and disabling it is silly, but hey), and that's the purpose of typeid. If you want to stringise type names at compile time, you have to do it yourself (via template or macros).