質問

ポリシーベースのクラスを設計しようとしています。特定のインターフェイスがポリシー自体によって実装されているため、クラスはポリシー自体がテンプレートです(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?

役に立ちましたか?

解決

これにより、ポリシークラスはインターフェイスクラスから継承する必要があります。

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

他のヒント

Boost :: MPLアプローチを試すこともできます:

TestInterfaceとtestimplをそのまま保持します。

#include <boost/mpl/inherit.hpp>

using namespace  boost::mpl;

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

動作するはずです

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top