考虑以下代码:
#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;
}
此代码打印“8”。我假设 fun() 中的 t 自动转换为 int&。
但是如果我用t=8
替换t+=8
,程序将无法编译。
为什么?
最佳答案
reference_wrapper<T>
有一个到 T &
的隐式转换运算符, 所以它会被转换成 T &
无论哪里 T &
是比 reference_wrapper<T>
更好的匹配.
在扩充赋值表达式中,唯一可行的运算符是int &operator+=(int &, int)
所以 int &
被提取出来。
在赋值表达式中,成员运算符reference_wrapper<int>::operator=(const reference_wrapper<int> &)
也可以,所以成员(member)运营商是首选;然后编译器尝试从常量 8
构造一个引用包装器,失败了。赋值运算符具有重新绑定(bind)的作用,这对于 tie
之类的设施来说是必需的。按预期工作。
这意味着引用包装器比 C++ 引用更接近于 Python 等语言中的引用:
#include <functional>
#include <iostream>
int main() {
int i = 1, j = 2;
std::ref(i) = j;
std::cout << i << '\n'; // prints '1'
}
关于c++ - std::reference_wrapper 何时转换为 T&?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13517223/