Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would say, just construct a <code>std::map</code> that maps the <code>enum</code> to a factory function (<code>boost::function&lt;&gt;</code>). Then you just add one entry for each type that you want, with its corresponding <code>enum</code>. To actually construct the factory functions. You can either have some <code>static Create()</code> function for each class and store a function pointer. Or, you can use Boost.Lambda <a href="http://www.boost.org/doc/libs/1_45_0/doc/html/lambda/le_in_details.html#lambda.construction_and_destruction" rel="nofollow">constructor/destructor</a> functors. Or, you can use <a href="http://www.boost.org/doc/libs/1_45_0/libs/bind/bind.html" rel="nofollow">Boost.Bind</a> to construct functors that wrap a factory function that requires some number of parameters. Here is an example:</p> <pre><code>#include &lt;boost/bind.hpp&gt; #include &lt;boost/function.hpp&gt; #include &lt;boost/lambda/construct.hpp&gt; #include &lt;map&gt; struct Base { }; struct Derived1 : public Base { }; struct Derived2 : public Base { static Base* Create() { return new Derived2; }; }; struct Derived3 : public Base { int value; Derived3(int aValue) : value(aValue) { }; static Base* Create(int aValue) { return new Derived3(aValue); }; }; enum DerivedCreate { ClassDerived1, ClassDerived2, ClassDerived3 }; int main() { std::map&lt; DerivedCreate, boost::function&lt; Base*() &gt; constructor_map; constructor_map[ClassDerived1] = boost::lambda::new_ptr&lt;Derived1&gt;(); constructor_map[ClassDerived2] = &amp;Derived2::Create; constructor_map[ClassDerived3] = boost::bind(&amp;Derived3::Create, 42); //now you can call any constructor as so: Base* ptr = constructor_map[ClassDerived2](); }; </code></pre> <p>I might have made some slight syntax mistakes, but basically you should be able make the above work. Also, the fact that you have several class templates plays no role, once they are instantiated to a concrete class (like <code>Class&lt;int&gt;</code> or <code>Class&lt;double&gt;</code>) they are just like any other class, and the above idea should remain valid.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload