代码之家  ›  专栏  ›  技术社区  ›  Frank

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

  •  2
  • Frank  · 技术社区  · 15 年前

    我正在尝试设计一个基于策略的类,其中某个接口是由策略本身实现的,因此该类派生自策略,该策略本身是一个模板(我从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 {
    
    };
    

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

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

    但它不能编译,因为

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

    我想 TestInterface::test() 是因为我们从 TestImpl1 ?

    2 回复  |  直到 15 年前
        1
  •  6
  •   sbi    15 年前

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

    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> {
      // ...
    };
    
        2
  •  1
  •   Anatoly Fayngelerin    15 年前

    您还可以尝试Boost::MPL方法:

    保持你的睾丸表面和睾丸正常:

    #include <boost/mpl/inherit.hpp>
    
    using namespace  boost::mpl;
    
    template <class TestPolicy>
    class Foo: public inherit2< TestPolicy, inherit2< TestInterface , empty_base >::type >::type
    {
    ...
    }
    

    应该工作