Reputation: 12929
I would like to know which way is the best to compare typeids. Or is there any difference between the two:
typeid(std::string&) == typeid(std::string{""})
typeid(std::string) == typeid(std::string{""})
As output they are both true, but i would like to know if there is something "deeper" to know.
Upvotes: 2
Views: 1101
Reputation: 73376
The excellent and well document answer from Evg tells you that both are equivalent.
But you also asked if there was something deeper to know. And yes there is:
name()
you must be aware that different types can have the same string representation. So, even if your equality is true, you cannot be sure that it's really the same types on both sides. typeid
operations for expressions of the same type may return different type_info
references. So by comparing the address of the of two typeids, you cannot be sure that it's two different types. So if you want to use typeid
to compare the runtime types, you should go for its hash_code()
(which is guaranteed to produce the same value for two equal type and which should give different values for different types, according to a non-normative remark in the standard ). Or even better, just compare the typeid
themselves with ==
as suggested by Artyer in the comments.
Upvotes: 1
Reputation: 26292
The standard reads [expr.typeid]:
When
typeid
is applied to a type-id, the result refers to astd::type_info
object representing the type of the type-id. If the type of the type-id is a reference to a possibly cv-qualified type, the result of thetypeid
expression refers to astd::type_info
object representing the cv-unqualified referenced type.
It follows from this quote that both comparisons are equivalent.
Upvotes: 7