我试图了解 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>
. 在阅读参考资料时,我+=
注意到std::reference_wrapper<int>
. 那么,如何c += 1;
有效?