// bind example #include <iostream> // std::cout #include <functional> // std::bind // a function: (also works with function object: std::divides<double> my_divide;) double my_divide (double x, double y) {return x/y;} struct MyPair { double a,b; double multiply() {return a*b;} }; int main () { using namespace std::placeholders; // adds visibility of _1, _2, _3,... // binding functions: auto fn_five = std::bind (my_divide,10,2); // returns 10/2 std::cout << fn_five() << '/n'; // 5 auto fn_half = std::bind (my_divide,_1,2); // returns x/2 std::cout << fn_half(10) << '/n'; // 5 auto fn_invert = std::bind (my_divide,_2,_1); // returns y/x std::cout << fn_invert(10,2) << '/n'; // 0.2 auto fn_rounding = std::bind<int> (my_divide,_1,_2); // returns int(x/y) std::cout << fn_rounding(10,3) << '/n'; // 3 MyPair ten_two {10,2}; // binding members: auto bound_member_fn = std::bind (&MyPair::multiply,_1); // returns x.multiply() std::cout << bound_member_fn(ten_two) << '/n'; // 20 注意,这里ten_two 是引用 不是复制
//===========================================================================================
auto bound_member_cpy = std::bind (&MyPair::multiply,ten_two);
std::cout << bound_member_cpy() << '/n'; // 这里调用的ten_two 是复制版本不是引用版本
auto bound_member_ref = std::bind (&MyPair::multiply,&ten_two); // returns ten_two.a
std::cout << bound_member_ref() << '/n'; // 这里才是引用版本 同理,下行是复制版本
//===============================================================================================
auto bound_member_data = std::bind (&MyPair::a,ten_two); // returns ten_two.a std::cout << bound_member_data() << '/n'; // 10 return 0; }
C++11 中引入 std::ref
用于取某个变量的引用,这个引入是为了解决一些传参问题。
std::ref 用于包装按引用传递的值。
std::cref 用于包装按const引用传递的值。
#include <functional> #include <iostream> void f(int& n1, int& n2, const int& n3) { std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '/n'; ++n1; // increments the copy of n1 stored in the function object ++n2; // increments the main()'s n2 // ++n3; // compile error } int main() { int n1 = 1, n2 = 2, n3 = 3; std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3)); n1 = 10; n2 = 11; n3 = 12; std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '/n'; bound_f(); std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '/n'; }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/282681.html