title: Problems with the universal factory method and the variadic templates
body: <p>I want to create something like an universal factory method - look at this one:</p>
  
  <pre><code>template &lt;class BaseType&gt;
  class Factory {
    public:
      template &lt;class ... Args&gt;
      static BaseType* Create(const Args&amp; ... args) {
        return new DerivedType(args ...);
      }
  };
  </code></pre>
  
  <p>Where the <code>DerivedType</code> is some other type derived from <code>BaseType</code> and defined in a different place.</p>
  
  <p>The problem is with storing <code>DerivedType</code>. I want to do it, for example, like this: </p>
  
  <pre><code>void f() {
    // Derived type may have more than one constructor,
    // that's why I suggest using of the variadic templates.
    BaseType* ptr1 = Factory&lt;BaseType&gt;::Create("abc", 5, 10.);
    BaseType* ptr2 = Factory&lt;BaseType&gt;::Create();
    ...
  }
  
  ...
  
  Factory&lt;BaseType&gt;::SetType&lt;MyDerivedType&gt;();
  f();
  
  Factory&lt;BaseType&gt;::SetType&lt;YourDerivedType&gt;();
  f();
  </code></pre>
  
  <p>I can set different derived types, but all of them are known at compile-time.
  I can't think of an appropriate technique to do this.</p>
  
  <p><strong>Question:</strong> Can you advise one?</p>
  
  <hr>
  
  <p>The rationale of doing this (thus, the original problem, if someone suggests the question is it-self the XY problem) - is an ability to unit-test some tricky parts of code. For example, if I have a code:</p>
  
  <pre><code>...
  Shuttle* shuttle1 = new ShuttleImpl("Discovery", Destination::Moon);
  Shuttle* shuttle2 = new ShuttleImpl();
  ...
  </code></pre>
  
  <p>And I don't want to really construct the shuttle each time I run unit-tests:</p>
  
  <pre><code>class Shuttle: public Factory&lt;Shuttle&gt; { ... }
  ...
  Shuttle* shuttle1 = Shuttle::Create("Discovery", Destination::Moon);
  Shuttle* shuttle2 = Shuttle::Create();
  ...
  </code></pre>
  
  <p>So, in the unit-test I can just do: <code>Shuttle::SetType&lt;TestShuttle&gt;();</code>.</p>
  
  <p>There may be more "testable" classes, that's why I need an universal factory for all of them:</p>
  
  <pre><code>class Car: public Factory&lt;Car&gt; { ... }
  class Driver: public Factory&lt;Driver&gt; { ... }
  ...
  </code></pre>