Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: Polymorphic container which can add several objects at once
    text
    copied!<p>Trying to re-factor some infrastructure code I've decided to use inheritance to achieve polymorphic behavior between several classes. The next step is to throw them in to a container, iterate over them and DoSomething();</p> <p>My current construction of the container is clumsy. Even if I use this <a href="https://stackoverflow.com/questions/41045/can-i-have-polymorphic-containers-with-value-semantics-in-c">elegant</a> solution for the container, construction is still a mess. </p> <pre><code>vector&lt;unique_ptr&lt;Parent&gt;&gt; vec; vec.push_back(unique_ptr&lt;Parent&gt;(new ChildA(var1, var2))); vec.push_back(unique_ptr&lt;Parent&gt;(new ChildB(var3, var4))); vec.push_back(unique_ptr&lt;Parent&gt;(new ChildC(var5, var6))); </code></pre> <p>ChildA, ChildB and ChildC are all polymorphic to one another. Var1 ... var6 may be from different types and are required for the construction of the child objects. </p> <p>I would like to create this vector in several places for usage. The problem is that the amount of children may vary and hence the data the children need for construction. Trying to walk the path of stdarg.h failed since this isn't supported:</p> <pre><code>if !defined(_WIN32) #error ERROR: Only Win32 target supported! #endif </code></pre> <p>How would you implement a factory method which constructs this array? </p> <p>UPDATE, desired solution:</p> <pre><code>vec = CreatePolyVec(var1, var2, typeInfo1, var3, var4, typeInfo2, var5, var6 typeInfo3); vec = CreatePolyVec(var1, var2, typeInfo1, var3, var4, typeInfo2); </code></pre> <p>line 1 will create the same array as above. line 2 will reuse the same code to create a similar vector but with one less object. Typeinfo holds the information required to create the object. </p> <p>This is a basic solution, a more advanced one will enforce the argument list in compile time. for example the following call to the function doesn't make sense:</p> <pre><code>vec = CreatePolyVec(var1, var2,typeinfo1, var3, var4, typeinfo2, var5); </code></pre> <p>not enough parameters to create the last child object.</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