Compile time typeid without RTTI with GCC

GCC supports compile time type operator with typeof.


First of all, turn back on RTTI.

Failing that, if you really *really* need to get a string representation of a type without it, with a little string manipulation, and careful consideration of the fact that you're writing non-standard code that might break if you upgrade GCC, or change platforms, or use a different set of options, you might be able to fake it.

#include <iostream>
#include <string>

std::string extract_type_name(const char* s) {
  //add logic her
  return s;
}

template<typename T>
std::string type_name() {
  static std::string s = extract_type_name(__PRETTY_FUNCTION__);
  return s;
}

int main() {
  std::cout << type_name<int>() << " " << type_name<std::string>() << std::endl;
}

The output of that function on ideone is

std::string type_name() [with T = int]
std::string type_name() [with T = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]

Assuming that __PRETTY_FUNCTION__ behaves the same with RTTI turned off, yanking out the T = blah bit shouldn't be overly difficult.

Also, keep in mind that typeid(blah).name() offers very few guarantees... I remember using it on one platform where the result for any user defined type was simply struct. Not overly useful. Relying on it is flimsy even with RTTI turned on [which you should do anyhow].


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
}

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

Tags:

C++

Reflection