使用 typeid 运算符的最佳选择
Best alternative for using typeid operator
我想知道哪种方式比较 typeid 最好。或者两者有什么区别:
typeid(std::string&) == typeid(std::string{""})
typeid(std::string) == typeid(std::string{""})
作为输出,它们都是真实的,但我想知道是否有什么 "deeper" 需要知道。
标准 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.
从这句话可以看出,这两个比较是等价的。
excellent and well document 告诉你两者是等价的。
但是你也问了有没有更深层次的东西要知道。是的,还有:
- 比较两个 typeids 时
name()
你必须知道不同的类型可以有相同的字符串表示。所以,即使你的平等是真的,你也不能确定它真的是两边的相同类型。
- 反之,同类型表达式的不同
typeid
操作可能return不同的type_info
引用。所以通过比较两个 typeid 的地址,你不能确定它是两个不同的类型。
所以如果你想使用typeid
来比较运行时类型,你应该在评论中找到它的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。
我想知道哪种方式比较 typeid 最好。或者两者有什么区别:
typeid(std::string&) == typeid(std::string{""})
typeid(std::string) == typeid(std::string{""})
作为输出,它们都是真实的,但我想知道是否有什么 "deeper" 需要知道。
标准 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.
从这句话可以看出,这两个比较是等价的。
excellent and well document
但是你也问了有没有更深层次的东西要知道。是的,还有:
- 比较两个 typeids 时
name()
你必须知道不同的类型可以有相同的字符串表示。所以,即使你的平等是真的,你也不能确定它真的是两边的相同类型。 - 反之,同类型表达式的不同
typeid
操作可能return不同的type_info
引用。所以通过比较两个 typeid 的地址,你不能确定它是两个不同的类型。
所以如果你想使用typeid
来比较运行时类型,你应该在评论中找到它的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。