Suppose I\'m given a C++ library full of inheritance. I\'m given a Base*
in a function when I know that it is actually pointing to a Derived
object and
When in doubt, you should prefer dynamic_cast
. It might be slower, but you probably won't notice the difference anyway.
If you need speed, use the following snippet:
template
Derived safe_static_cast(Base b)
{
assert((void*)dynamic_cast(b) && "safe_static_cast failed!");
return static_cast(b);
}
Or something equivalent.
The idea is that in debug builds, it checks that it's indeed what you thought it would be, and it release builds... well everything has already been tested, hasn't it ?