سؤال

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 to T &, so it will be converted to T & wherever a T & is a better match than a reference_wrapper<T>.

In the augmented assignment expression, the only viable operator is int &operator+=(int &, int) so the int & 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 constant 8, which fails. The assignment operator has the effect of rebinding, which is necessary for facilities like tie to work as expected.

This means that reference wrappers are closer to references in languages like Python than C++ references:

#include <functional>
#include <iostream>

int main() {
    int i = 1, j = 2;
    std::ref(i) = j;
    std::cout << i << '\n';                 // prints '1'
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top