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
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,197exact_cast
:78,366,879
Which is a 5.6% speedup. This is for non-trivial CPU-bound code. (It does no I/O)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With