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 ?

Enjolras
  • 371
  • 2
  • 8

1 Answers1

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() {
        ...
    }
Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • Yes, I know i could go this way, but i don't like it much, since the base class has to know about the derived class... – Enjolras Jul 26 '12 at 08:00
  • 1
    @Enjolras the base class has to know about the derived class, either at compile time or run time; that means CRTP of virtual methods. – ecatmur Jul 26 '12 at 08:03
  • @Enjolras The base class only knows about the derived class's interface, not its implementation. – TemplateRex Jul 26 '12 at 08:22