将容器存储在boost :: variant中

Baz*_*Baz 2 c++ boost std

最后一行:

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 );
Run Code Online (Sandbox Code Playgroud)

给我错误:

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))
Run Code Online (Sandbox Code Playgroud)

这里有什么问题?你认为有一个容器类型C这样的定义是明智的吗?

我在整个代码中使用以下类型:

typedef boost::variant<int, float, ...> Type; 
Run Code Online (Sandbox Code Playgroud)

您是否认为使用此容器定义更明智:

typedef std::vector<Type> C; // mixed container
Run Code Online (Sandbox Code Playgroud)

为什么?

Kon*_*lph 5

你的问题是这个

C container(std::vector<float>());
Run Code Online (Sandbox Code Playgroud)

是一个函数声明(这是最令人烦恼的解析)(一个函数container,它将一个函数std::vector<float>作为唯一的参数返回,并返回C).简单修复:额外的括号:

C container((std::vector<float>()));
Run Code Online (Sandbox Code Playgroud)

您使用容器的事实variant与问题无关.同样的情况也会发生boost::variant<int, float>.