Avoid dynamic_cast for downcasting for source type

How can I safely reset (i.e. return null on error) the exact type of the base object without compromising the performance of dynamic_cast and without the need to add support code to every class that I use?

+3
source share
1 answer

dynamic_cast will move throughout the inheritance tree to see if the conversion you want is possible. If all you need is a direct downcast for the same type as the object, and you don’t need the ability to cross cast, pass through virtual inheritance, or translate the actual type of the object into the base class, 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 translation operators, i.e.

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

Edit: I tested this in the project I'm working on. My results from QueryPerformanceCounter :
dynamic_cast : 83,024,197
exact_cast : 78,366,879
Which is 5.6% acceleration. This is for non-trivial CPU bound code. (No input / output)

+2
source

Source: https://habr.com/ru/post/1203009/


All Articles