std::bind()之std::placeholders理解记录

使用 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 占位符的理解与学习,希望能帮助到有需要的同学。

  • 6
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值