mercredi 1 juin 2016

Factory with switch over enum that instantiates templates

I have the following hierarchy pattern in various places in the codebase:

enum DerivedType {
    A, B, C };

class Base {
public:
  static Base* Create(DerivedType t);
};

template <DerivedType T>
class Derived : public Base {
};

The Create method returns a new object of class Derived<A>, Derived<B>, or Derived<C>, depending on its argument:

Base* Base::Create(DerivedType t) {
  switch (t) {
  case A: return new Derived<A>;
  case B: return new Derived<B>;
  case C: return new Derived<C>;
  default: return NULL;
  }
}

The problem is that there are many such Base -> Derived hierarchies, with essentially the same implementation of Create() copy-pasted all over the place. Is there an elegant, yet easy-to-understand way to avoid duplication here?

Aucun commentaire:

Enregistrer un commentaire