带模板的“虚拟”方法

时间:2012-07-26 07:39:08

标签: c++ templates

我有以下基类:

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就是虚拟的。我怎样才能实现这一目标?

1 个答案:

答案 0 :(得分: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() {
        ...
    }