I’ve got a template class:
template <class T>
class TemplateClass
{
//irrelevant what this class does
}
And two classes, one base and one class which derives from it:
class Base
{
//does whatever
}
class Derived : public Base
{
}
Now I want to assemble a function which can deal with TemplateClass of templated type Base* as well as TemplateClass of templated type Derived* without having to implement the function separately for both types.
In code, this is what I’d like to be able to do:
void DoSomething(const TemplateClass<Base *> &tc)
{
//do something
}
And somewhere else in the code:
TemplateClass<Base *> a;
TemplateClass<Derived *> b;
DoSomething(a); //Works
DoSomething(b); //Doesn't work, but I'd like it to work
Is there a way to implement this without having to manualy overload DoSomething for Derived* ?
Sadly, C++ does not support template covariance, so you cannot do that automatically. As a workaround, you could do something like this:
Demo on ideone.