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
You can use the "Curiously Recurring Template Pattern" http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
Using this pattern, the base class takes the derived class type as a template parameter, meaning that the base class can cast itself to the derived type in order to call functions in the derived class. It's a sort of compile time implementation of virtual functions, with the added benefit of not having to do a virtual function call.
template
class A {
public:
virtual ~A() {}
template
void method(T &t) { static_cast(*this).methodImpl(t); }
};
class B : public A
{
friend class A;
public:
virtual ~B() {}
private:
template
void methodImpl(T &t) {}
};
It can then be used like this...
int one = 1;
A *a = new B();
a->method(one);