I have a plain old CRPT (please don’t get distracted by access restrictions – the question is not about them):
template<class Derived>
class Base {
void MethodToOverride()
{
// generic stuff here
}
void ProblematicMethod()
{
static_cast<Derived*>(this)->MethodToOverride();
}
};
that is as usual intended to be used like this:
class ConcreteDerived : public Base<ConcreteDerived> {
void MethodToOverride()
{
//custom stuff here, then maybe
Base::MethodToOverride();
}
};
Now that static_cast bothers me. I need a downcast (not an upcast), so I have to use an explicit cast. In all reasonable cases the cast will be valid since the current object is indeed of the derived class.
But what if I somehow change the hierarchy and the cast now becomes invalid?
May I somehow enforce a compile-time check that an explicit downcast is valid in this case?
At compile-time you can only check the static types, and that’s what
static_castalready does.Given a
Base*, it is only, and can only be, known at run-time what its dynamic type is, that is, whether it actually points to aConcreteDerivedor something else. So if you want to check this, it has to be done at runtime (for example by usingdynamic_cast)