Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding dynamic_cast for downcasting to the original type

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?

like image 999
Dan Avatar asked Oct 08 '22 05:10

Dan


1 Answers

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)

like image 193
Dan Avatar answered Oct 13 '22 10:10

Dan