在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,太尼玛的好用了,万金油啊!