Consider the following code:
#include <iostream>
#include <functional>
using namespace std;
template<class T>
void fun(T t)
{
t+=8;
}
int main()
{
int i = 0;
fun(ref(i));
cout << i << endl;
}
This code prints “8”. I assume that the t in fun() is automatically converted to an int&.
But if I replace t+=8 with t=8, the program will not compile.
Why?
reference_wrapper<T>has an implicit conversion operator toT &, so it will be converted toT &wherever aT &is a better match than areference_wrapper<T>.In the augmented assignment expression, the only viable operator is
int &operator+=(int &, int)so theint &is extracted.In the assignment expression, the member operator
reference_wrapper<int>::operator=(const reference_wrapper<int> &)is also available, so the member operator is preferred; the compiler then attempts to construct a reference wrapper from the constant8, which fails. The assignment operator has the effect of rebinding, which is necessary for facilities liketieto work as expected.This means that reference wrappers are closer to references in languages like Python than C++ references: