2012-10-05 32 views
2

最後一行在這裏:存儲容器在一個boost ::變種

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

是給我的錯誤:

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

這裏有什麼問題嗎?在你看來,有一個容器類型C有這樣的定義是明智的嗎?

我使用下面的類型在我的代碼:

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

你認爲這將是明智使用這個容器定義來代替:

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

爲什麼?

回答

5

你的問題是,這

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

是一個函數聲明(這是most vexing parse)(函數container這需要一個函數返回std::vector<float>作爲其唯一的參數,並返回C)。簡單的解決辦法:額外的括號:

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

的事實,你正在使用的variant容器是無關緊要的問題。 boost::variant<int, float>也會發生同樣的情況。

+0

謝謝!你認爲我應該使用第一個typedef ... C;定義還是第二? – Baz

+0

@Baz無論你對誰都有意義,這兩者不可互換。 –

+0

我更喜歡第一個,因爲它定義了一個包含相同類型值的容器。如果我希望在容器中具有不同類型的值,我將使用第二個定義,而實際上我不這樣做。 – Baz

相關問題