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.
Just like dynamic_cast, the typeid does not always need to use RTTI mechanism to work correctly. If the argument of the typeid expression is non-polymorphic type, then no runtime check is performed. Instead, the information about the type is known at the compile-time.
-fno-rtti. Disable generation of information about every class with virtual functions for use by the C++ runtime type identification features (` dynamic_cast ' and ` typeid '). If you don't use those parts of the language, you can save some space by using this flag.
Since typeid is applied to a type rather than an object, there is no runtime type information, so that overhead won't be a problem.
Run-Time Type Discovery (Reflection) Note: The compiler option Project > Options > C++ Compiler > Enable RTTI refers to standard C++ RTTI.
There is another solution with its pros and cons:
typedef void* TypeId;
template<class T>
TypeId TypeIdNoRTTI() //this function is instantiated for every different type
{
//WARNING: works only inside one module: same type coming from different module will have different value!
static T* TypeUniqueMarker = NULL; //thus this static variable will be created for each TypeIdNoRTTI<T> separately
return &TypeUniqueMarker; //it's address is unique identifier of TypeIdNoRTTI<T> type
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With