I have some code that behaves like this:
class Base {};
class MyClass : public Base {};
MyClass* BaseToMyClass(Base* p)
{
MyClass* pRes = dynamic_cast<MyClass*>(p);
assert(pRes);
return pRes;
}
Is there a way to add a compile time check so I can catch calls to this function where p is not an instance of MyClass? I had a look at Alexandrescu’s SUPERSUBCLASS function but I’m not sure if it can do the job.
Thanks!
Generally, if you want to check this at compile-time, you’d take the derived class as an argument.
However, if the only thing you have is a
Base*or aBase&, then you cannot know whether it refers to aMyClassobject. It’s the very nature of run-time polymorphism that this is to be found out at run-time. This check can only be done where theMyClassobject/reference/pointer is converted to aBase*/Base&. That’s whydynamic_cast<>()was invented.Your function basically is a
safe_cast. If you put it into the right syntax, it looks like this: