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?
Here's the simplest ID I can think of. MyObject obj; uint32_t id = reinterpret_cast<uint32_t>(&obj); At any given time, this ID will be unique across the application. No other object will be located at the same address.
The typeid operator provides a program with the ability to retrieve the actual derived type of the object referred to by a pointer or a reference. This operator, along with the dynamic_cast operator, are provided for runtime type identification (RTTI) support in C++.
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.
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 astd::type_info
object, that can be used as index in associative and unordered associative containers. The relationship withtype_info
object is maintained through a pointer, therefore type_index is CopyConstructible and CopyAssignable.
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