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.