Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a value to a std::reference_wrapper

Tags:

c++

c++11

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:

error: use of deleted function 'std::reference_wrapper<_Tp>::reference_wrapper(_Tp&&) [with _Tp = int]'

like image 590
masoud Avatar asked Mar 17 '13 17:03

masoud


1 Answers

Use the get() member function:

v[0].get() = 1111; // ok

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 );

the int literal is converted to a reference wrapper, which fails, and is the error message you see.

Alternatively, you could call the conversion operator explicit (static_cast<int&>(v[0]) = 1111;), but better use the get() method as showed above.

like image 156
ipc Avatar answered Oct 09 '22 00:10

ipc