我正在尝试了解 std::ref 的工作原理。
#include <functional>
#include <iostream>
template <class C>
void func(C c){
c += 1;
}
int main(){
int x{3};
std::cout << x << std::endl;
func(x);
std::cout << x << std::endl;
func(std::ref(x));
std::cout << x << std::endl;
}
Output : 3 3 4
在上面的代码中,我认为模板参数C
第三个函数调用被实例化为 std::reference_wrapper<int>
.
阅读时the reference ,
我注意到没有 +=
std::reference_wrapper<int>
中的运算符.
那么,c += 1;
怎么样?有效吗?
最佳答案
how is
c += 1;
valid?
因为reference_wrapper<int>
可隐式转换为 int&
通过其转换运算符;如果操作数类型本身没有合适的重载,则考虑对操作数进行隐式转换。
关于c++ - reference_wrapper 和 std::ref 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16542391/