Search code examples
c++rttitypeid

Numeric unique identifier of a class via typeid


The typeid operator in C++ returns an object of class std::type_info which can yield its textual name. However, I'm just interested in getting an unique numeric identifier for any polymorphic class. (unique in the scope of a single program run - not necessarily between runs)

In practice, I could just dereference the pointer and read the vptr's contents - but this would be neither elegant nor portable. I prefer a portable way.

Can I use the typeid operator somehow to have a "safe" numerical identifier for a class? For example, can I count on the address of resulting std::type_info structure to be the same for every typeid call on a given class? Or perhaps the name() pointer itself?


Solution

  • std::type_index (C++ 11) can be used in containers to store values based on type. It won't give you a number though.

    std::type_index index = std::type_index (typeid (int));
    

    More: http://en.cppreference.com/w/cpp/types/type_index

    The type_index class is a wrapper class around a std::type_info object, that can be used as index in associative and unordered associative containers. The relationship with type_info object is maintained through a pointer, therefore type_index is CopyConstructible and CopyAssignable.