views:

70

answers:

2

I'm trying to design a policy-based class, where a certain interface is implemented by the policy itself, so the class derives from the policy, which itself is a template (I got this kind of thinking from Alexandrescu's book):

#include <iostream>
#include <vector>

class TestInterface {
public:
  virtual void test() = 0;
};

class TestImpl1 {
public:
  void test() {std::cerr << "Impl1" << std::endl;}
};

template<class TestPolicy>
class Foo : public TestInterface, TestPolicy {

};

Then, in the main() function, I call test() on (potentially) various different objects that all implement the same interface:

int main() {
  std::vector<TestInterface*> foos;
  foos.push_back(new Foo<TestImpl1>());
  foos[0]->test();
  delete foos[0];
  return 0;
}

It doesn't compile, though, because

the following virtual functions are pure within ‘Foo<TestImpl1>’:
  virtual void TestInterface::test()

I thought TestInterface::test() is implemented because we derive from TestImpl1?

+5  A: 

For this to work the policy class needs to inherit from the interface class:

class TestInterface {
public:
  virtual void test() = 0;
};

template< class Interface >
class TestImpl1 : public Interface {
public:
  void test() {std::cerr << "Impl1" << std::endl;}
};

template<class TestPolicy>
class Foo : public TestPolicy<TestInterface> {
  // ...
};
sbi
+1  A: 

You could also try a boost::mpl approach:

keeping your TestInterface and TestImpl as they are:

#include <boost/mpl/inherit.hpp>

using namespace  boost::mpl;

template <class TestPolicy>
class Foo: public inherit2< TestPolicy, inherit2< TestInterface , empty_base >::type >::type
{
...
}

should work

Anatoly Fayngelerin