1

Here is some code:

class IWorker {
public:
    virtual void Do(int x) const = 0;
};

class TSomeWorker : public IWorker {
    void Do(int x) const {
        // ...
    }
};

Now, imagine that we need to refactor it in such way that function Do should become template (int changes into some T). I know that C++ does not allow to create template virtual functions. Is there any alternative?

typedef
  • 1,800
  • 3
  • 11
  • 19
  • 1
    Similar question: http://stackoverflow.com/questions/7648430/designing-hiearchical-classes-with-template-function/7648621#7648621 – jpalecek Jul 02 '12 at 18:40
  • 2
    and another: http://stackoverflow.com/questions/7968023/c-virtual-template-method – jpalecek Jul 02 '12 at 18:41

2 Answers2

2

It depends on your specific needs. But according to what you posted I would suggest:

template<typename T>
class IWorker {
public:
    virtual void Do(T x) const = 0;
};

template<typename T>
class TSomeWorker : public IWorker<T> {
    void Do(T x) const {
        // ...
    }
};
tenfour
  • 36,141
  • 15
  • 83
  • 142
  • The problem here is that when I use class IWorker in some other classes I have to make them to be templates too. But they're not. The nature of the class says that only the funciton Do is templated :) – typedef Jul 02 '12 at 18:45
  • A generalized solution to this is described in the answers @jpalecek linked to. If you want a more specific solution to your problem, you have to give more context. – tenfour Jul 02 '12 at 18:49
0

So, you want to mix static polymorphism (templates) and run-time polymorphism (virtual functions), but those are orthogonal. In such case, you need to cast :

class IWorker {
public:
    virtual void Do(void* x) const = 0;
};

template< typename T >
class TSomeWorker : public IWorker {
    void Do(void* x) const {
        T* realX = reinterpret_cast< T* >( x );
        // ...
    }
};
BЈовић
  • 62,405
  • 41
  • 173
  • 273