Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If i had to define a variant object, i'd probably start with the following :</p> <pre><code>template&lt;typename Type1, typename Type2&gt; class VariantVisitor; template&lt;typename Type1, typename Type2&gt; class Variant { public: friend class VariantVisitor&lt;Type1, Type2&gt;; Variant(); Variant(Type1); Variant(Type2); // + appropriate operators = ~Variant(); // deal with memory management private: int type; // 0 for invalid data, 1 for Type1, 2 for Type2 void* data; }; template&lt;typename Visitor, typename Type1, typename Type2&gt; class VariantVisitor { private: Visitor _customVisitor; public: void doVisit(Variant&lt;Type1, Type2&gt;&amp; v) { if( v.type == 1 ) { _customVisitor( *(Type1*)(v.data)); } else if( v.type == 2 ) { _customVisitor( *(Type2*)(v.data)); } else { // deal with empty variant } } }; template&lt;typename Visitor, typename Type1, typename Type2&gt; void visit( Visitor visitor, Variant&lt;Type1, Type2&gt; v ) { VariantVisitor&lt;Visitor, Type1, Type2&gt;(visitor).doVisit(v); } </code></pre> <p>then use <a href="http://www.boost.org/doc/libs/release/libs/mpl/doc/refmanual/vector.html" rel="nofollow noreferrer">MPL vectors</a> to make the approach work for more than just two different types.</p> <p>In the end, you could write something like this :</p> <pre><code>Variant&lt;Type1, Type2&gt; v; class MyVisitor { public: operator()(Type1); operator()(Type2); }; MyVisitor visitor; v = Type1(); visit(visitor, v); v = Type2(); visit(visitor, v); </code></pre> <p>NB : there is no chance this code compiles, but this describes the ideas i'd use.</p>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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