I've seen solutions to this problem that suggest using
if( dynamic_cast<DerviedType1*>( base ) ){
// Do something
}
else if( dynamic_cast<DerviedType2*>( base ) ){
// Do something else
}
else if( dynamic_cast<DerviedType3*>( base ) ){
// Do another thing
}
// and so on
While functional, this solution is far from elegant, and I was hoping that there was a single-line solution, along the lines of decltype
or typeid
, neither of which help me here.
My specific problem is as follows. I have a function that will take a pointer to an instance of the base class as an argument. This function will then call a template function within that takes the derived type as its parameter. E.g.
void myFunc( Base *base )
{
myTemplateFunc<Derived>();
}
I would like to keep my code simple, without a laundry list of if
statements, but I'm not sure how to go about it. It should be noted that the Base
object itself will not be passed into the template function, only it's type.
For reference, I'm looking for something along the lines of
void myFunc( Base *base )
{
myTemplateFunc<decltype(base)>();
}
but this will only return the Base
type, which doesn't help me here.