使用std::ref可以在模板傳參的時候傳入引用,否則無法傳遞
&是類型說明符, std::ref 是一個函數,返回 std::reference_wrapper(類似於指針)
用std::ref 是考慮到c++11中的函數式編程,如 std::bind.
例子:
1 #include <iostream> 2 #include <functional> 3 4 void foo(int& a) { 5 ++a; 6 } 7 8 void foo2(const int& a){ 9 sdt::cout<<"a="<<a<<"\n"; 10 } 11 12 13 void test_function(std::function<void(void)> fun) { 14 fun(); 15 } 16 17 int main() { 18 int a = 1; 19 20 std::cout << "a = " << a << "\n"; 21 test_function(std::bind(foo, a)); 22 std::cout << "a = " << a << "\n"; 23 test_function(std::bind(foo, std::ref(a))); 24 std::cout << "a = " << a << "\n"; 25 test_function(std::bind(foo2,std::cref(a))); 26 std::cout<<"a =" <<a<<"\n"; 27 28 return 0; 29 }
輸出:
a=1
a=1(因為std::bind將參數拷貝了,不對參數直接操作。而foo改變的是拷貝,不影響a)
a=2(若要使用引用來改變原來參數,就用std::ref() )
a=2 (std::cref() 用於const引用)