2012-11-08 24 views
10

這編譯:使用boost ::分配:: LIST_OF

std::vector<int> value = boost::assign::list_of(1)(2); 

但不是這樣的:

Constructor(std::vector<int> value) 
{ 
} 

Constructor (boost::assign::list_of(1)(2)); 

是否有初始化傳遞給構造矢量一行代碼的解決方案?

更妙的是,如果構造複製到一個類變量,採取了參考,而不是:

Constructor(std::vector<int>& value) 
{ 
    _value = value; 
} 

UPDATE

如果我嘗試以下方法:

enum Foo 
{ 
    FOO_ONE, FOO_TWO 
}; 

class Constructor 
{ 
public: 
    Constructor(const std::vector<Foo>& value){} 
}; 

Constructor c(std::vector<Foo>(boost::assign::list_of(FOO_ONE))); 

我得到編譯器錯誤:

error C2440: '<function-style-cast>' : cannot convert from 'boost::assign_detail::generic_list<T>' to 'std::vector<_Ty>' 
1>   with 
1>   [ 
1>    T=Foo 
1>   ] 
1>   and 
1>   [ 
1>    _Ty=Foo 
1>   ] 
1>   No constructor could take the source type, or constructor overload resolution was ambiguous 
+0

你可以給編譯器錯誤信息嗎? –

+0

@Kevin MOLCARD添加編譯器錯誤 – Baz

+2

[看起來像這是錯誤](https://svn.boost.org/trac/boost/ticket/7364)。 –

回答

19

這是一個煩人的問題,我們也有過一段時間。我們固定它通過使用convert_to_container方法:

Constructor c(boost::assign::list_of(1)(2).convert_to_container<std::vector<int> >()); 

有更多的問題與的std ::名單使用構造函數了。請參閱Pass std::list to constructor using boost's list_of doesn't compile以獲得相應的答案。

+0

您是否發現爲什麼需要調用'conver_to_container'函數? –

0

我使用這個模板,使性病的臨時實例:: vector的就地:

#include <vector> 
namespace Util { 
//init vector 
template <typename ELEMENT_TYPE > struct vector_of 
    : public std::vector<ELEMENT_TYPE> 
{ 
    vector_of(const ELEMENT_TYPE& t) 
    { 
     (*this)(t); 
    } 
    vector_of& operator()(const ELEMENT_TYPE& t) 
    { 
     this->push_back(t); 
     return *this; 
    } 
}; 
}//namespace Util 

用法是這樣的:

Constructor (Util::vector_of<int>(1)(2)); 

構造函數簽名是這樣的:

Constructor(const std::vector<int>& value) 
{ 
    _value = value; 
} 
相關問題