bind
函数可以将自变量绑定到可调用对象。
例如:对一个需要接收两个参数的方法,指定占位符,使其变为一个接收一个参数的对象:
void product(double x, double y) { std::cout << x << "*" << y << " == " << x * y << std::endl; } double arg[] = { 1, 3, 5 }; std::for_each(&arg[0], arg + 3, std::bind(product, 3, std::placeholders::_1)); cout << endl; cout << endl;
对成员函数绑定对象:
class Abc { public: void display_sum(int a1, int a2) { cout << "a1: " << a1 << ", " << a2 << endl; } }; Abc a; auto f = std::bind(&Abc::display_sum, &a, 100, std::placeholders::_1); f(20);