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?
How can I downcast safely (ie returning null on failure) to the exact type
Share
dynamic_castwill 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:The semantics are exactly the same as for other cast operators, ie
Edit: I have tested this on a project I am working on. My results from
QueryPerformanceCounterare:dynamic_cast: 83,024,197exact_cast:78,366,879Which is a 5.6% speedup. This is for non-trivial CPU-bound code. (It does no I/O)