使用 std::bind() 需要添加 #include<functional> 头文件
std::bind()函数接受一个可调用对象及其参数(如果有的话),形成一个新的可调用对象。
可调用对象:普通函数体,Lambda表达式(匿名函数),类成员函数,静态成员函数,仿函数(重载了括号运算符的类)等都可以称为可调用对象。
void TestFunc(int a, char b, float c) {
cout << a << endl;
cout << b << endl;
cout << c << endl;
return;
}
TestFunc 为普通函数体,可以称为一个可调用对象,其含有三个参数。
auto bindTest1 = std::bind(TestFunc, std::placeholders::_1, 'b', 12.4f);
bindTest1(123);
bindTest1 为 使用 std::bind 接受 TestFunc 可调用对象及其参数 封装而成的一个新的可调用对象;可通过 bindTest1() 进行调用。
std::placeholders:代表占位符,表示在 TestFunc 中占据第一个参数的位置(此处与 "_1" 没关系,仅仅因为 std::placeholders 出现在第一个参数的位置上)
std::placeholder::_1 中的 "_1": 表示新的可调用对象中的第一个参数,即 bindTest1(123) 中的参数 123
auto bindTest1 = std::bind(TestFunc, std::placeholders::_1, 'b', 12.4f);
bindTest1(123);
等价于:
将 bindTest1(123) 中的第一个参数 123 传递给 TestFunc 中的第一个参数 int a, 'b' 传递给 char b, 12.4f 传递给 float c
auto bindTest2 = std::bind(TestFunc, std::placeholders::_2, std::placeholders::_1, 12.4f);
bindTest2('c', 321);
等价于:
将 bindTest2('c', 321) 中的第二个参数 321 传递给 TestFunc 中的第一个参数 int a;
将 bindTest2('c', 321) 中的第一个参数 'c' 传递给 TestFunc 中的第二个参数 char b;
将 12.4f 传递给 TestFunc 中的第三个参数 float c;
auto bindTest3 = std::bind(TestFunc, std::placeholders::_2, std::placeholders::_3, std::placeholders::_1);
bindTest3(12.4f, 6, 'a');
等价于:
将 bindTest3(12.4f, 6, 'a') 中的第二个参数 6 传递给 TestFunc 中的第一个参数 int a;
将 bindTest3(12.4f, 6, 'a') 中的第三个参数 'a' 传递给 TestFunc 中的第二个参数 char b;
将 bindTest3(12.4f, 6, 'a') 中的第一个参数 12.4f 传递给 TestFunc 中的第三个参数 float c;
以上为对 std::bind 中 std::placeholders 占位符的理解与学习,希望能帮助到有需要的同学。