2012-11-08 26 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; 
} 
相关问题