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]'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With