2010-03-07 36 views
2

我試圖設計一個基於策略的類,其中某個接口是由策略本身實現的,所以這個類來自策略,它本身就是一個模板(我從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

回答

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

您也可以嘗試一個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 
{ 
... 
} 

應該工作