I have a class hierarchy where I want to introduce a method template that would behave like if it was virtual. For example a simple hierarchy:
class A {
vi
As you may know, you cannot have templates for virtual functions, since the entirety of the virtual functions is part of the class type and must be known in advance. That rules out any simple "arbitrary overriding".
If it's an option, you could make the template parameter part of the class:
template class A
{
protected:
virtual void method(T &);
};
template class B : public A
{
virtual void method(T &); // overrides
};
A more involved approach might use some dispatcher object:
struct BaseDispatcher
{
virtual ~BaseDispatcher() { }
template void call(T & t) { dynamic_cast(this)->method(t); }
};
struct ConcreteDispatcher : BaseDispatcher
{
template void method(T &);
};
class A
{
public:
explicit A(BaseDispatcher * p = 0) : p_disp(p == 0 ? new BaseDispatcher : p) { }
virtual ~A() { delete p_disp; };
private:
BaseDispatcher * p_disp;
template void method(T & t) { p_disp->call(t); }
};
class B : public A
{
public:
B() : A(new ConcreteDispatcher) { }
// ...
};