1

Suppose I have in a templated derived class in C++ for which I want to choose template arguments at runtime according to some conditions. Something like:

class Base {
  public:
    virtual void do_something() = 0;
};

template <typename T, typename U>
class Derived : public Base {
  public:
    virtual void do_something() { ... }
};

Base* obj;
if (... /* runtime conditon #1 */ )
  obj = new Derived<T1, U1>();
else if (... /* runtime condition #2 */ )
  obj = new Derived<T1, U2>();
...

obj->do_something();

I'd like to refer to this situation in general, but don't know how to call it. Is there some standard name for it? Is it some kind of design pattern or idiom?

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93
  • 3
    Factory design pattern? – Nawaz Jul 24 '13 at 16:33
  • I was going to suggest factory as well. From wikipedia: "The factory determines the actual concrete type of object to be created, and it is here that the object is actually created (in C++, for instance, by the new operator). However, the factory only returns an abstract pointer to the created concrete object." – slaterade Jul 24 '13 at 16:35
  • Just as a quick sanity check, you know all of the different types of possible template instantiations at compile-time, right? The template arguments must be known at compile-time. If this is so, you may want to refer to [this](http://stackoverflow.com/questions/17378961/elegant-way-to-implement-extensible-factories-in-c/17409442#17409442) post. – Suedocode Jul 24 '13 at 16:36
  • 4
    @Giswin: Really? There is a difference between *"class template containing virtual function(s)"* and *"virtual function template"*. The former is allowed, the latter is not. – Nawaz Jul 24 '13 at 16:39
  • Thanks, factory is fine. Just don't know it this kind of factory, i.e. single templated derived class in C++, does not have a special name. Seemingly not... – Daniel Langr Jul 24 '13 at 16:49
  • @Aggieboy: Yes, I know all possible combinations of template arguments at compile time. – Daniel Langr Jul 24 '13 at 16:49

1 Answers1

1

This looks like the factory pattern to me, using different template instantiations instead of separate explicit derived classes as may be more typical.

Mark B
  • 95,107
  • 10
  • 109
  • 188