Is std::type_index unique?

429 Views Asked by At

I hope to use std::map to store information for different datatype by type_index, learned from cppreference.com.

For example:

#include <typeindex>
class A{};
class B{};
int main()
{
    map<type_index, string> info{
        {type_index[typeid(A)], "Information for class A."},
        {type_index[typeid(B)], "Information for class B."}
    };
}

typeid() will return a struct type_info.

But I learnt that type_info.hash_code() may be not unique.Different type may have same hash_code. I wonder if type_index is unique ?

1

There are 1 best solutions below

0
HolyBlackCat On

Yes, std::type_index is unique. It's said to work as if it held a pointer to std::type_info.

Even though you can get different pointers for the same type, they're not compared directly. Rather, std::type_info::before() is used.