什么时候使用'typeid'最好的解决方案? [英] When is using 'typeid' the best solution?

查看:149
本文介绍了什么时候使用'typeid'最好的解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多原因不使用 typeid 。除了使用 type_info (实现定义的行为)的成员,通常(总是)可以使用其他C ++语言功能提供类似的功能,例如:重载,虚函数



因此,排除依赖于实现定义行为的用法,任何人都有一个现实世界的例子,其中 typeid boost :: any 使用

code> typeid 来实现 any_cast

 模板< typename T> any_cast(const any& other){
if(typeid(T)!= other.type())throw bad_any_cast();

//...actual cast here ...
}

您不能确定 T 是多态的,因此 dynamic_cast 是不成问题的,在 boost :: any 调用中的类型现在已经丢失,因此其他类型的转换都不能提供任何类型的安全性。


There are many reasons not to use typeid. Other than for using members of type_info (implementation defined behavior), it is usually (always?) possible to provide similar functionality using other C++ language features, eg: overloading, virtual functions etc.

So, excluding usage that relies on the implementation defined behavior, does anybody have a real world example where typeid is the best solution?

解决方案

boost::any uses typeid to implement any_cast.

template<typename T> any_cast(const any& other) {
   if(typeid(T) != other.type()) throw bad_any_cast();

   //...actual cast here...
}

You can't be sure T is polymorphic, so dynamic_cast is out of the question, and the enclosed type within the boost::any call is lost by now, so none of the other casts can provide any sort of type safety.

这篇关于什么时候使用'typeid'最好的解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆