如何为由 std :: reference_wrapper ?包装的项目指定值
How can we assign a value to an item wrapped by std::reference_wrapper?
int a[] = {0, 1, 2, 3, 4}; std::vector <std::reference_wrapper<int>> v(a, a+5); v[0] = 1234; // Error, can not assign value !遇到错误,直接分配已删除:
Accoring to error, direct assignment is deleted:
错误:使用删除的函数'std :: reference_wrapper< _Tp> :: reference_wrapper(_Tp&&)[with _Tp = int] p>
error: use of deleted function 'std::reference_wrapper<_Tp>::reference_wrapper(_Tp&&) [with _Tp = int]'
推荐答案
使用 get()函数:
v[0].get() = 1111; // ok这里是 std :: reference_wrapper 的所有成员函数的列表。由于 是 operator = :
Here is a list of all member functions of std::reference_wrapper. Since there is a operator=:
reference_wrapper& operator=( const reference_wrapper<T>& other );int文本转换为引用包装器,失败,并且是您看到的错误消息。
the int literal is converted to a reference wrapper, which fails, and is the error message you see.
或者,您可以调用转换操作符explicit( static_cast< int&>(v [0])= 1111; ),但更好地使用 get()方法,如上所示。
Alternatively, you could call the conversion operator explicit (static_cast<int&>(v[0]) = 1111;), but better use the get() method as showed above.
更多推荐
为std :: reference
发布评论