views:

141

answers:

2

I have tried reading:

http://www.boost.org/doc/libs/1_41_0/boost/variant.hpp


http://www.codeproject.com/KB/cpp/TTLTyplist.aspx


and chapter 3 of "Modern C++ Design"

but still don't understand how variants are implemented. Can anyone paste a short example of how to define something like:

class Foo {
  void process(Type1) { ... };
  void process(Type2) { ... };
};


Variant<Type1, Type2> v;

v.somethingToSetupType1 ...;

somethingToTrigger process(Type1);

v.somethingToSetupType2 ...;

somethingToTrigger process(Type2);

Thanks!

+1  A: 

If i had to define a variant object, i'd probably start with the following :

template<typename Type1, typename Type2>
class VariantVisitor;

template<typename Type1, typename Type2>
class Variant
{
public:
   friend class VariantVisitor<Type1, Type2>;
   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<typename Visitor, typename Type1, typename Type2>
class VariantVisitor 
{
   private:
     Visitor _customVisitor;
   public:
   void doVisit(Variant<Type1, Type2>& v)
   {
      if( v.type == 1 )
      {
          _customVisitor( *(Type1*)(v.data));
      }
      else if( v.type == 2 )
      {
          _customVisitor( *(Type2*)(v.data));
      }
      else
      {
         // deal with empty variant
      }
   }
};
template<typename Visitor, typename Type1, typename Type2>
void visit( Visitor visitor, Variant<Type1, Type2> v )
{
  VariantVisitor<Visitor, Type1, Type2>(visitor).doVisit(v);
}

then use MPL vectors to make the approach work for more than just two different types.

In the end, you could write something like this :

Variant<Type1, Type2> v;
class MyVisitor
{
  public:
  operator()(Type1);
  operator()(Type2);
};

MyVisitor visitor;
v = Type1();
visit(visitor, v);
v = Type2();
visit(visitor, v);

NB : there is no chance this code compiles, but this describes the ideas i'd use.

Benoît
I doubt that it is anything like Boost.Variant, though. For example, isn't sizeof(variant<X, Y>) dependent on the largest of the types - which indicates that the values are not stored as a `void*`? - Unfortunately, the source is too long and complicated for me to read (one probably needs to fight the compiler for every little step towards the goal, so I'm grateful I can just use other peoples' work if I need to :))
UncleBens
I completely agree. I would never use a personal version of variants. Boost.Variant works fine and i don't really need to know how. I was simply explaining how it *could* be done.
Benoît
+1  A: 
xzqx