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?