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

1 回答 1

4

您可以通过奇怪的重复模板模式 (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() {
        ...
    }
于 2012-07-26T07:57:58.030 回答