Aftershock
Aftershock

Reputation: 5351

Why is this boost::variant example not working?

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> ]

Upvotes: 2

Views: 5743

Answers (1)

Baffe Boyois
Baffe Boyois

Reputation: 2140

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]);

Upvotes: 11

Related Questions