Avoiding dynamic_cast for downcasting to the original type

爱⌒轻易说出口 提交于 2019-12-10 18:29:32

问题


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?


回答1:


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);

Edit: 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)



来源:https://stackoverflow.com/questions/11494524/avoiding-dynamic-cast-for-downcasting-to-the-original-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!