使用模板的"虚拟"方法

"virtual" method with templates

本文关键字:虚拟 方法      更新时间:2023-10-16

我有以下基类:

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将是虚拟的。我该如何实现这个目标?

您可以通过Curioly 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() {
        ...
    }