我试图做到这一点:maitain字符串的两个向量即一个向量商店的价值观和相同价值的第二个门店引用。我想用的boost ::的reference_wrapper 会做的伎俩,但似乎不会。我的平台是VISUAL C ++ 2008。
I am trying to do this: maitain two vectors of strings whereby one vector stores values and the second stores references of the same values. I thought using boost::reference_wrapper would do the trick but it seems it won't. My platform is Visual C++ 2008.
std::vector<std::string> str_vec; str_vec.push_back("abc"); str_vec.push_back("cde"); str_vec.push_back("fgh"); std::vector<boost::reference_wrapper<std::string> > str_view; for(std::vector<std::string>::iterator it = str_vec.begin(); it != str_vec.end(); ++it) { str_view.push_back(*it); }这是错误:
错误C2664:'的std ::矢量&lt; _Ty> ::的push_back':不能从性病:: basic_string的&LT转换参数1; _Elem,_Traits,_AX>'到'常量的boost ::参考
error C2664: 'std::vector<_Ty>::push_back' : cannot convert parameter 1 from std::basic_string<_Elem,_Traits,_Ax>' to 'const boost::reference
我可以使用的boost :: shared_ptr的但是我想一个更好的参考前presses我的意图。这code大概可以工作在C ++ 11使用的std ::的reference_wrapper ,但不是提供给我现在。
I could use boost::shared_ptr but I thought a reference better expresses my intent. This code can probably work in C++11 using std::reference_wrapper but that is not available to me right now.
推荐答案是的,可以。该文件指出,这是复制构造和可分配这是容器模板参数所需的概念。但是,你需要使用的boost :: REF 或的boost :: CREF 以创建类型的对象的reference_wrapper 。有没有隐式转换,这就是为什么你的code不起作用。
Yes, it can. The documentation states that it is CopyConstructible and Assignable which are required concepts for container template arguments. But you need to use boost::ref or boost::cref to create objects of type reference_wrapper. There is no implicit conversion and this is why your code does not work.
请注意,的std ::的reference_wrapper 之间的细微差别和的boost ::的reference_wrapper 是只有 STD 版本适用于函子。
Be aware that a slight difference between std::reference_wrapper and boost::reference_wrapper is that only the std version works with functors.
例如:
std::vector<std::string> str_vec; str_vec.push_back("abc"); str_vec.push_back("cde"); str_vec.push_back("fgh"); std::vector<boost::reference_wrapper<std::string> > str_view; std::transform(begin(str_vec), end(str_vec), std::back_inserter(str_view), boost::ref<std::string>);如果你不喜欢这一点,希望有从原来的值隐式转换,你可能想使用:
If you dislike that and would like to have implicit conversion from the original value, you might want to use:
template<typename T> class my_ref_wrap : public boost::reference_wrapper<T> { public: my_ref_wrap(T& t) : boost::reference_wrapper<T>(t) {} }; std::vector<my_ref_wrap<std::string> > str_view; std::copy(begin(str_vec), begin(str_vec), std::back_inserter(str_view));虽然我不会这么做的。
Although I would not do that.
更多推荐
你可以使用boost ::的reference
发布评论