02 std::bind

std::bind

bind函数看作是一个通用的函数适配器。
它接受一个可调用对象,生成一个新的可调用对象来“适应”原对象的参数列表。

void fun(int x, int y, int z)
{
    cout<< x <<" "<< y <<" "<< z <<endl;
}
01 绑定参数
auto f1 = std::bind(fun,1,2,3);

f1();//print:1 2 3
02 绑定参数的第三个参数为3, 第一、第二个参数由调用者指定
auto f2 = std::bind(fun, placeholders::_1, placeholders::_2, 3);

f1(1, 2);//print:1 2 3
03 绑定参数的第三个参数为3, 第一、第二个参数由调用者的第二、第一个参数指定。
auto f3 = std::bind(fun, placeholders::_2, placeholders::_1, 3);

f3(1,2);//print:2  1  3
04 绑定参数一个参数为n , 第二个参数由调用者指定
int n = 2;
int m = 3;
auto f4 = std::bind(fun, 1, n, placeholders::_1);
f4(m); //print:1 2 3
05 绑定类的成员函数
A a;
auto f5 = std::bind(&A::fun, a, placeholders::_1, placeholders::_2);

std::function<void(int,int)> f6 = std::bind(&A::fun,a,std::placeholders::_1,std::placeholders::_2);
f5(10,20);//==>调用a.fun(10,20)==>print:10 20
posted @ 2018-12-06 23:52  osbreak  阅读(295)  评论(0编辑  收藏  举报