bind是什么
bind是一个函数模板,它就像一个函数包装器 ( 适配器 ) , 接受一个可 调用对象 ,生成一个新的可调用对象来 “ 适应 ” 原对象的参数列表 。
bind怎么使用
int Add(int a, int b, int c)
{return a + b + c;
}class Sub
{
public:int sub(int a, int b){return a - b;}
};
int main()
{//表示绑定函数plus 参数分别由调用 Add 的第一,二,三个参数指定function<int(int, int, int)> func1 = bind(Add, placeholders::_1, placeholders::_2, placeholders::_3);cout << func1(33, 22, 11) << endl;//表示绑定函数 plus 的第一,二,三的参数的值分别为: 1, 2 , 3function<int(int, int, int)> func2 = bind(Add, 1, 2, 3);cout << func2(33, 22, 11) << endl;Sub s;// 绑定成员函数function<int(Sub *,int, int)> func3 = bind(&Sub::sub, placeholders::_1,placeholders::_2,placeholders::_3);cout << func3(&s,2, 1) << endl;return 0;
}
bind的使用场景
bind可以改变传入参数的个数!!!
我们想在一个类外使用这个类的非静态成员函数时,我们可以使用bind绑定这个函数,让我们不必传入this指针
// 绑定成员函数function<int(Sub *,int, int)> func3 = bind(&Sub::sub, placeholders::_1,placeholders::_2,placeholders::_3);cout << func3(&s,2, 1) << endl;// 绑定成员函数 优化function<int(int, int)> func4 = bind(&Sub::sub,&s,placeholders::_1, placeholders::_2);cout << func4( 2, 1) << endl;