避免dynamic_cast向下转换为原始类型 [英] Avoiding dynamic_cast for downcasting to the original type

查看:312
本文介绍了避免dynamic_cast向下转换为原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何安全地(即返回null失败)到基础对象的确切类型,而不会招致 dynamic_cast 的性能惩罚,而不必放支持代码在每个类中使用?

How can I downcast safely (ie returning null on failure) to the exact type of the underlying object, without incurring the performance penalty of dynamic_cast, and without having to put support code in every class I use?

推荐答案

dynamic_cast 完整的继承树,看看你想要的转换是否可能。如果你想要的是直接向下转换为相同的类型作为对象,你不需要交叉强制转换的能力,跨转换虚拟继承,或者转换为基类对象的实际类型,以下代码将工作:

dynamic_cast will traverse the entire inheritance tree to see if the conversion you want is possible. If all you want is a direct downcast to the same type as the object, and you don't need the ability to cross cast, to cast across virtual inheritance, or to cast to a base class of the object's actual type, the following code will work:

template<class To>
struct exact_cast
{
    To result;

    template<class From>
    exact_cast(From* from)
    {
        if (typeid(typename std::remove_pointer<To>::type) == typeid(*from))
            result = static_cast<To>(from);
        else
            result = 0;
    }

    operator To() const
    {
        return result;
    }
};

语义与其他转换运算符完全相同,即

The semantics are exactly the same as for other cast operators, ie

Base* b = new Derived();
Derived* d = exact_cast<Derived*>(b);

编辑:我已经在我正在开发的项目上测试过了。我的来自 QueryPerformanceCounter 的结果是:

dynamic_cast :83,024,197

exact_cast :78,366,879

这是一个5.6%的加速。这是为非平凡的CPU绑定代码。 (它没有I / O)

I have tested this on a project I am working on. My results from QueryPerformanceCounter are:
dynamic_cast: 83,024,197
exact_cast:78,366,879
Which is a 5.6% speedup. This is for non-trivial CPU-bound code. (It does no I/O)

这篇关于避免dynamic_cast向下转换为原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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