
there is great disadvantage of variant in performance terms. One can't create instance of variant with proper type inside without calling copy costructor.
I think this depends on your compiler/optimizer. The following test
code was compiled with MSVC9, release mode (/O2 /Ob2 /Oi /Ot /Oy /GL),
see comments inside the code:
int main()
{
struct A
{
A() : a_(1)
{}
int a_;
};
struct B
{
B() : b_(2.0)
{}
double b_;
};
struct Visitor : boost::static_visitor<>
{
void operator()(const A &a) const
{ std::cout << a.a_; }
void operator()(const B &b) const
{ std::cout << b.b_; }
void operator()(int i) const
{ std::cout << i; }
void operator()(const std::string &s) const
{ std::cout << s; }
};
B b;
boost::variant v(b);
// the previous construction compiled into 1
instruction (even a call to the constructor was optimized out):
// movsd xmm0,mmword ptr
[__real@4000000000000000 (41FD68h)]
boost::apply_visitor(Visitor(), v);
std::string s = "abcd";
boost::variant