开发者

How to have a policy class implement a virtual function?

开发者 https://www.devze.com 2022-12-22 17:15 出处:网络
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

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;
}开发者_JS百科;

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?


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> {
  // ...
};


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号