Edgepo1nt
Edgepo1nt

Reputation: 303

Interface for template methods

I have a class Foo that provides some sort of functionality. In order to maintain modularity, Foo is to be an interface (That is, a C++ class with only abstract methods), and an implementation of Foo can choose how exactly to implement the functionality. However, my interface includes a template method. That is,

class Foo
{
public:
        template<class T>
        void functionality(const T&);
};

It is impossible in C++ to have template methods virtual. Is there any technique that can achieve a similar result (Modularity and Polymorphism) with template methods?

Upvotes: 2

Views: 2878

Answers (1)

RandyGaul
RandyGaul

Reputation: 1915

You can't have run-time polymorphism mixed directly with templating. However another layer of indirection might help. Here's a contrived example:

template <typename T>
inline void *New( void )
{
  return new T( );
}

This function will allow the user to dynamically allocate any type of object so long as a default constructor exists. Now take a function pointer and assign it to this new function:

void *(*NewFuncPtr)( void ) = New<int>;
int *i = (int *)NewFuncPtr( );

The function pointer itself isn't templated, but can point to a function that is templated. Perhaps this can solve your situation too.

Upvotes: 1

Related Questions