c++11绑定器bind

在c++11中,为函数的参数绑定增加了binder(绑定器),比以前版本的bind1st和bind2nd方便很多,功能也强大很多。


配合auto关键字,bind可以实现将参数绑定成固定值和改变参数的顺序。


当遇见重载的函数是,需要在绑定是,将函数指针(函数名)强制转换为相应的具体类型才行。


具体的实例见下面的代码,具体使用见注释:

<pre name="code" class="cpp">
#include <iostream>
#include <string>
#include <functional>

using namespace std;
<span style="background-color: rgb(51, 255, 51);">using namespace std::placeholders</span>;<span style="color:#ffcc66;"> </span><span style="color:#330033;background-color: rgb(255, 255, 0);"> //bind中用到的_1,_2的命名空间</span><span style="color:#ffcc66;">
</span>
void func(int num, const string& str)
{
	cout<<"func("<<num<<","<<str<<")"<<endl;
}

void overloaded(int num)
{}

void overloaded(float f)
{}

int main()
{
	//把第二个参数绑定为固定的值
	string str = "buaa";
	auto f1 = bind(func,<span style="background-color: rgb(51, 255, 51);"> _1, str</span>);
	f1(16);

	//重新安排参数的顺序
	auto f2 = bind(func, <span style="background-color: rgb(51, 255, 51);">_2, _1</span>);
	f2("test", 32);

	//重载函数的时候绑定必须制定绑定重载的类型
	auto f3 = bind(<span style="background-color: rgb(51, 255, 51);">(void(*)(float))overloaded</span>, _1);

	system("pause");
	return 0;
}


 具体的下过见下图所示: 


此外不得不赞下auto,太尼玛的好用了,万金油啊!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值