1

I have the following base class :

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);

};

with

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

And other specializations for each composed object.

But, i need construct to be implemented by the derived class. Without templates, Construct whould be virtual. How can i achieve this goal ?

4

1 に答える 1

4

You can do this with compile-time polymorphism, via the 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>();
    }

And in Derived, write:

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 に答える