为std :: reference_wrapper分配一个值 [英] Assign a value to a std::reference_wrapper

查看:169
本文介绍了为std :: reference_wrapper分配一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为由 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_wrapper分配一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆