Alberto
Alberto

Reputation: 12929

Best alternative for using typeid operator

I would like to know which way is the best to compare typeids. Or is there any difference between the two:

  1. typeid(std::string&) == typeid(std::string{""})
  2. 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

Answers (2)

Christophe
Christophe

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:

  • When comparing two typeids 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.
  • In the opposite direction, different 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

Evg
Evg

Reputation: 26292

The standard reads [expr.typeid]:

When typeid is applied to a type-id, the result refers to a std​::​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 the typeid expression refers to a std​::​type_­info object representing the cv-unqualified referenced type.

It follows from this quote that both comparisons are equivalent.

Upvotes: 7

Related Questions