Baz
Baz

Reputation: 13135

Storing containers in a boost::variant

The last line here:

typedef boost::variant<std::vector<int>, std::vector<float>> C; 

class A: public boost::static_visitor<>
{
public:
    void operator()(const std::vector<int>& value) const
    {
    }

    void operator()(const std::vector<float>& value) const
    {
    }
};

C container(std::vector<float>());
boost::apply_visitor(A(), container );

Is giving me the error:

c:\boost_1_49_0\boost\variant\detail\apply_visitor_unary.hpp(60): error C2228: left of '.apply_visitor' must have class/struct/union
1>          type is 'boost::variant<T0_,T1> (__cdecl &)'
1>          with
1>          [
1>              T0_=std::vector<int>,
1>              T1=std::vector<float>
1>          ]
1>          c:\visual studio 2010\projects\db\xxx\main.cpp(255) : see reference to function template instantiation 'void boost::apply_visitor<A,C(std::vector<_Ty> (__cdecl *)(void))>(Visitor &,Visitable (__cdecl &))' being compiled
1>          with
1>          [
1>              _Ty=float,
1>              Visitor=A,
1>              Visitable=C (std::vector<float> (__cdecl *)(void))

What is the problem here? Is it sensible in you opinion to have a container type C which such a definition?

I am using the following type throughout my code:

typedef boost::variant<int, float, ...> Type; 

Do you think it would be wiser to use this container definition instead:

typedef std::vector<Type> C; // mixed container

Why?

Upvotes: 2

Views: 339

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

Your problem is that this

C container(std::vector<float>());

is a function declaration (that’s the most vexing parse) (a function container which takes a function returning std::vector<float> as its sole argument, and returns C). Easy fix: extra parentheses:

C container((std::vector<float>()));

The fact that you’re using containers in the variant is irrelevant to the problem. The same would have happened with boost::variant<int, float>.

Upvotes: 5

Related Questions