Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numeric unique identifier of a class via typeid

Tags:

c++

typeid

rtti

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?

like image 616
Kos Avatar asked Apr 19 '11 16:04

Kos


People also ask

How to generate unique id in c++?

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.

What is the use of Typeid ()?

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

Is Typeid a runtime?

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.


1 Answers

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.

like image 162
lietus Avatar answered Sep 21 '22 15:09

lietus