Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Something like what you want to achieve can be accomplished with inheritance. That is, the parent class has the variable name you want your template to have.</p> <pre><code>struct ItemNull {}; template &lt;typename X, typename Y = ItemNull&gt; class Item : public X, public Y {}; template &lt;typename T&gt; struct HasPosition { T Position; }; template &lt;typename T&gt; struct HasMomentum { T Momentum; }; Item&lt; HasPosition&lt;float&gt; &gt; myItem1; myItem1.Position = 0.123f; Item&lt; HasPosition&lt;float&gt;, HasMomentum&lt;float&gt; &gt; myItem2; myItem2.Position = 0.1f; myItem2.Momentum = 0.2f; </code></pre> <p>The optional second argument allows for composition, as illustrated in <code>myItem2</code>. To add a third field, you could add to the tail, or expand from the front:</p> <pre><code>template &lt;typename T&gt; struct HasName { T Name; }; Item &lt; HasPosition&lt;float&gt;, Item&lt; HasMomentum&lt;float&gt;, HasName&lt;std::string&gt; &gt; &gt; myItem3; myItem3.Position = 0.1f; myItem3.Momentum = 0.2f; myItem3.Name = "Adam"; Item &lt; Item &lt; HasPosition&lt;float&gt;, HasMomentum&lt;float&gt; &gt;, HasName&lt;std::string&gt; &gt; myItem4; myItem4.Position = 0.1f; myItem4.Momentum = 0.2f; myItem4.Name = "Adam"; </code></pre> <p>My personal preference is for the former of the two methods, because I find it to be a more intuitive way to extend it beyond 3 fields. The <code>Item</code> template syntax could probably be simplified using variadic template arguments.</p> <p>The <code>Has...</code> templates could be machine generated or a macro could be created to make adding new fields a relatively simple task. </p> <pre><code>#define MAKE_HAS(X) template &lt;typename T&gt; struct Has##X { T X; } MAKE_HAS(Position); MAKE_HAS(Momentum); MAKE_HAS(Name); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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