Comparing two type_info from typeid() operator
比较两个typeid()结果可以吗?cppreference对此运算符有以下说明:
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.
1 2 3 4 5 6 | 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 |
我的理解是,返回是对类型为_info的静态l值的引用。这意味着&ti1==&ti2不能保证在相同类型中是相同的。而是说使用散列代码或std::type_index类。但是,它没有提到是否直接比较类型:
1 | ti1 == ti2; |
保证是真实的。我以前就用过这个,文档是否暗示这是有保证的?
1 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.