bind包装器
调用bind的一般形式:
auto newCallable = bind(callable,arg_list);
其中,newCallable本身是一个可调用对象,arg_list是一个逗号分隔的参数列表,对应给定的 callable的参数。
当我们调用newCallable时,newCallable会调用callable,并传给它arg_list中 的参数。
bind的使用
#include<iostream> #include<functional> using namespace std; int Add(int a, int b) { cout << a << " " << b << endl; return a + b; } class Sub { public: int sub(int a, int b) { cout << a << " " << b << endl; return a - b; } double mul(int a, int b, double rate) { return a * b * rate; } static int test(int a, int b) { return a + b; } }; int main(void) { function<int(int, int)>func1 = bind(Add, placeholders::_1, placeholders::_2); function<int(int, int)>func2 = bind(Add, placeholders::_2, placeholders::_1); func1(1, 2); func1(2, 1); function<int(int, int)>func3 = bind(&Sub::sub,Sub(), placeholders::_1, placeholders::_2); function<int(int, int)>func4 = bind(&Sub::sub,Sub(), placeholders::_2, placeholders::_1); func3(5, 6); func4(5, 6); function<int(int, int)>func5 = bind(&Sub::mul, Sub(), placeholders::_1, placeholders::_2, 1.5); function<double(int, int)>func6 = bind(&Sub::mul, Sub(), placeholders::_1, placeholders::_2, 1.5); cout << func6(3,3)<<endl; function<int(int, int)>func7 = bind(&Sub::test, placeholders::_1, placeholders::_2); cout << func7(10, 20)<<endl; return 0; }