如何让策略类实现虚函数?

Fra*_*ank 2 c++ oop policy inheritance templates

我正在尝试设计一个基于策略的类,其中某个接口由策略本身实现,因此该类派生自策略,它本身就是一个模板(我从Alexandrescu的书中得到了这种思考):

#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 {

};
Run Code Online (Sandbox Code Playgroud)

然后,在main()函数中,我test()(可能)调用所有实现相同接口的各种不同对象:

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

但是,它不会编译,因为

the following virtual functions are pure within ‘Foo<TestImpl1>’:
  virtual void TestInterface::test()
Run Code Online (Sandbox Code Playgroud)

我认为TestInterface::test()是实施的,因为我们来源于TestImpl1

sbi*_*sbi 6

为此,策略类需要从接口类继承:

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> {
  // ...
};
Run Code Online (Sandbox Code Playgroud)