1、std::bind
用来绑定函数调用的参数,用于解决我们有时候可能并不一定能够一次性获得调用某个函数的全部参数,通过这个函数,我们可以将部分调用参数提前绑定到函数身上成为一个新的对象,然后在参数齐全后,完成调用的场景。
2、std::placeholders
定义:
namespace placeholders
{
extern /* unspecified */ _1;
extern /* unspecified */ _2;
extern /* unspecified */ _3;
// ...
}
其中_1, _2, _3是未指定的数字对象,用于function的bind中。 _1用于代替回调函数中的第一个参数, _2用于代替回调函数中的第二个参数,以此类推。
3、std::bind与std::placeholders相结合使用的例子
#include <functional>
#include <iostream>
int foo(int a, int b, int c)
{
std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
return a + b + c;
}
int main(int argc, char** argv)
{
// 将参数 1,2 绑定到函数 foo 上,但是使用 std::placeholders::_1 来对第一个参数进行占位
auto bindFoo = std::bind(foo, std::placeholders::_1, 1,2);
// 这时调用 bindFoo 时,只需要提供第一个参数即可
std::cout << bindFoo(5) << std::endl;
return 0;
}
Program stdout:
a = 5, b = 1, c = 2
8