std::type_info
123
std::type_info ti_1&=typeid(some_object); std::type_info& ti_2&=typeid(some_other_object); if (ti_1.operator==(ti_2)) // do something
123456789101112131415161718192021222324252627282930313233
#include <typeinfo> #include <typeindex> #include <cassert> #include <functional> #include <iostream> template < typename A, typename B > void foo( const A& a, const B& b ) { // the result of typeid() is a reference to *const* std::type_info const std::type_info& tinfo_a = typeid(a) ; const std::type_info& tinfo_b = typeid(b) ; // objects of type std::type_info are EqualityComparable bool dynamic_types_are_the_same = tinfo_a == tinfo_b ; bool static_types_are_the_same = typeid(A) == typeid(B) ; // but they are not CopyAssignable //std::type_info temp = tinfo_a ; // *** error, copy constructor is private // std::type_index provides a thin CopyAssignable, LessThanComparable wrapper // over std::type_info. It can be used as a key type in associative containers // and unordered associative containers // http://en.cppreference.com/w/cpp/types/type_index std::type_index tindex[] = { tinfo_a, tinfo_b, typeid(A), typeid(B) } ; assert( dynamic_types_are_the_same == ( tindex[0] == tindex[1] ) ) ; assert( static_types_are_the_same == ( tindex[2] == tindex[3] ) ) ; bool before = tindex[0] < tindex[2] ; std::hash<std::type_index> hash ; for( auto ti : tindex ) std::cout << hash(ti) << '\n' ; }