2012-07-26 63 views
1

我有以下的基类:“虚拟” 方法使用模板

template <template<class Type> class T2> 
class FundamentalClass { 
    typename T2<double> *_compose1; 
    typename T2<int> *_compose2; 

protected: 
    FundamentalClass(); // Insert constructors here. 

    template<class Strategy> 
    T2<typename Strategy::Type> *Construct(void); 

public: 
    template <class Strategy> 
    T2<typename Strategy::Type> *GetComposedObject(void); 

}; 

template< template<class Type> class T2> 
template<> 
T2<double> *FundamentalClass<T2<double> >::GetComposedObject<DoubleStrategy>(void) { 
    if(NULL == _compose1) { 
     _compose1 = Construct<DoubleStrategy>(void); 
    } 
    return _compose1; 
} 

和其他特对于每个组成对象。

但是,我需要构造由派生类实现。如果没有模板,Construct应该是虚拟的。我怎样才能达到这个目标?

回答

4

你可以编译时多态性做到这一点,通过Curiously Recurring Template Pattern (CRTP)

template <template<class Type> class T2, class Derived> 
class FundamentalClass { 
    ... 

    template<class Strategy> 
    T2<typename Strategy::Type> *Construct() { 
     return static_cast<Derived *>(this)->DoConstruct<Strategy>(); 
    } 

而且在Derived,写:

template <template<class Type> class T2> 
class Derived: public FundamentalClass<T2, Derived<T2> > 
{ 
public: 
    template<class Strategy> 
    T2<typename Strategy::Type> *DoConstruct() { 
     ... 
    } 
+0

是的,我知道我可以走这条路,但我不因为基类必须知道派生类... – Enjolras 2012-07-26 08:00:41

+1

@Enjolras基类必须在编译时或运行时知道派生类;这意味着虚拟方法的CRTP。 – ecatmur 2012-07-26 08:03:40

+0

看起来合法!你是对的。 – Enjolras 2012-07-26 08:13:25