Search code examples
c++typeid

Comparing two type_info from typeid() operator


Is it OK to compare the results from two typeid() results? cppreference has this note about this operator:

There is no guarantee that the same std::type_info instance will be referred to by all evaluations of the typeid expression on the same type, although std::type_info::hash_code of those type_info objects would be identical, as would be their std::type_index.

const std::type_info& ti1 = typeid(A);
const std::type_info& ti2 = typeid(A);

assert(&ti1 == &ti2); // not guaranteed
assert(ti1.hash_code() == ti2.hash_code()); // guaranteed
assert(std::type_index(ti1) == std::type_index(ti2)); // guaranteed

My understanding is that the the return is a reference to a static L value of type type_info. It's saying &ti1 == &ti2 is not guaranteed to be the same for the same types. It instead says to use the hash code or the std::type_index class. However it doesn't mention if comparing the types directly:

ti1 == ti2; 

is guaranteed to be true. I've used this before, does the documentation implicitly mean this is guaranteed?


Solution

  • std::type_info is a class-type, which means that the ti1 == ti2 expression will trigger an overloaded operator==. Its behavior is described by [type.info]/p2:

    bool operator==(const type_info& rhs) const noexcept;
    

    Effects: Compares the current object with rhs.

    Returns: true if the two values describe the same type.