MechaTheo MechaTheo - 23 days ago 6
C++ Question

Overriding template methods

I'm trying to override a template method.
Here is a minimal example:

#include <iostream>

class Base
{
public:
template <typename T>
void print(T var)
{
std::cout << "This is a generic place holder!\n";
}
};

class A: public Base
{
public:
template <typename T>
void print(T var)
{
std::cout << "This is A printing " << var << "\n";
}
};

class B: public Base
{
public:
template <typename T>
void print(T var)
{
std::cout << "This is B printing " << var << "\n";
}
};


int main()
{
Base * base[2];
base[1] = new A;
base[2] = new B;

base[1]->print(5);
base[2]->print(5);

delete base[1];
delete base[2];
return 0;
}


The output is in both cases
This is a generic place holder!

How can i achieve that the methods of the derived classes are called?

If the method would not be a template, i could define it
virtual
and it would work as expected (already tried that), but it needs to be a template. So what am i doing wrong?

Answer

First A member function template cannot be virtual, and a member function template in a derived class cannot override a virtual member function from the base class.

As your code, the type of the pointer are Base*, so in template member function instantiation, the function in the Base is instantiated, that's why the function is base is called.

If you use A* and B*, the functions in the children will be instantiated and called.