Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out if std::type_index is unique for my compiler?

Tags:

c++

c++11

Does the standard prescribe that an invocation of std::type_index(typeid(obj)) will be unique to that type? I couldn't find information on this. From type_info::name() I got this:

Returns an implementation defined null-terminated character string containing the name of the type. No guarantees are given, in particular, the returned string can be identical for several types and change between invocations of the same program.

(source: http://en.cppreference.com/w/cpp/types/type_info/name)

Which leads me to believe that maybe the mangled names / typeids are not necessarily unique. Yet the page for std::type_index specifically uses the assumption that these types are unique in its "usage example".

So how can I know if the typeid for my compiler is unique, and what the likelihood for a collision is? Further, is there any way of getting some sort of identifier (whether a string or otherwise) that we can know is unique to the type?

Demangling is not an option because it is too slow for very large types, but my guess is that if the implementation provides a facility to demangle a name, then the mangled name should be unique for that type in that implementation anyway, correct?

like image 403
quant Avatar asked Nov 07 '14 05:11

quant


1 Answers

The name function on a type_info is not guarenteed to be useful. An implementation could probably return "" for everything and be compliant. In practice it is not always "", and it can be used for debugging, but only that.

However, type_info == and before and hash_code do not rely on the name.

type_index is a wrapper around a pointer to a type_info that uses the info's methods to produce a Regular type (can be copied, stored, etc). It is distinct for distinct types.


Now, in practice, the problem is that on some C++ platforms, two different dynamic libraries with the exact same type in each (but not exported from one) have different type_info but the same .name().

You may want these to have equal names, or you may want to compare type_infos.

Both are problems.

like image 61
Yakk - Adam Nevraumont Avatar answered Nov 15 '22 20:11

Yakk - Adam Nevraumont