Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 - typeid uniqueness

Tags:

c++

c++11

typeid

In C++11, I am using this

typeid(T).name() 

for my own hash computation. I don't need the result to be same between the program runs or compilations. I just need it to be unique for the types. I know, that it can return same name for different types, but it is usually with const, pointers etc. In my case, T is only class XY, struct XX or derived types.

In this case, can I assume, that T will be unique?

like image 590
Martin Perry Avatar asked Nov 01 '16 10:11

Martin Perry


2 Answers

You should use std::type_index for mapping purposes.

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 119
StoryTeller - Unslander Monica Avatar answered Oct 03 '22 01:10

StoryTeller - Unslander Monica


std::type_info::name is implementation-defined, so you shouldn't rely on it being unique for different types.

Since you're doing this for hash computation, you should use std::type_info::hash_code instead. Although this doesn't guarantee that the values will be unique, the standard says that implementations should try and return different values for different types. So long as your hash map implementation has reasonable collision handling, this should be sufficient for you.

like image 39
TartanLlama Avatar answered Oct 03 '22 01:10

TartanLlama