tags:

views:

421

answers:

1

I am getting to know boost::variant. I think this example should work.

#include <boost/fusion/sequence.hpp>
#include <boost/fusion/include/sequence.hpp>

#include <boost/variant/variant.hpp>
#include <string>
#include <vector>
#include <iostream>
#include <boost/variant/get.hpp>
boost::variant< bool,long,double,std::string,
std::vector<boost::variant<bool> > > v4;
void main()
{

    std::vector<boost::variant<bool> > av (1);
    v4= av;
    try
    {
    bool b=
    boost::get<bool> (v4[0]); // <--- this is line 20
    std::cout << b;


    }
    catch (boost::bad_get v)
    {
    std::cout << "bad get" <<std::endl; 
    }
}

I get a compilation error:

d:\m\upp\boosttest\main.cpp(20) : error C2676: binary '[' : 'boost::variant' do es not define this operator or a conversion to a type acceptable to the predefined operator with [ T0_=bool, T1=long, T2=double, T3=std::string, T4=std::vector> ]

+6  A: 

v4[0] is not valid since v4 is a variant, not a vector. You need to use boost::get to retrieve the vector stored in it first. So, line 20 should be

boost::get<bool>(boost::get<std::vector<boost::variant<bool> > >(v4)[0]);

Baffe Boyois
Ugh! Man that's ugly!
JRL
A typedef for `std::vector<boost::variant<bool> >` helps a little. Not using variants of vectors of variants helps more :)
Baffe Boyois
varnie
oops, Baffe Boyois said that already;)
varnie
@varnie or at least by non-const reference.
rlbond
What difference does it meake if I use reference or not?
Aftershock
If you're catching a base class exception, like std::exception, then you won't get the same error reporting from derived exceptions. I think it's called slicing? But with a reference the exception won't be copied (wrongly) and it will retain the derived class' properties.
Jonas