1、基本概念
bind函数定义在头文件 functional 中。可以将 bind 函数看作一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对象来“适应”原对象的参数列表。——《C++Primer 5th》
2、bind的参数
-
-
-
-
using namespace std;
-
using namespace std::placeholders;
-
-
int main(void)
-
{
-
void confun(int a, int b, int c);
-
auto con = bind(confun, 3, _2, _1);
-
con( 5, 4);
-
}
-
void confun(int a,int b,int c)
-
{
-
cout << "a=" << a << ends << "b=" << b << ends << "c=" << c << endl;
-
}
_2 ,_1 为占位符,在(3)中详解。这里需要知道的是bind可以改变一个可调用对象的参数列表生成一个新的可调用对象去被调用。
3、用bind重排参数顺序
-
-
-
-
using namespace std;
-
using namespace std::placeholders;
-
-
int main(void)
-
{
-
void confun(int a, int b, int c);
-
auto con = bind(confun, 3, _2, _1);
-
con( 5, 4);
-
}
-
void confun(int a,int b,int c)
-
{
-
cout << "a=" << a << ends << "b=" << b << ends << "c=" << c << endl;
-
}
你会发现调用con时传入的顺序是 5,4 但是输出结果却是 b=4 c=5 。这就是占位符的作用,_2接受con的第二个参数4,_1接受con的第一个参数 。3, _2,_1又对应的是confun的a,b,c 所以 a=3,b=4,c=5.
如果还不清楚,再看下面这个例子
-
-
-
-
using namespace std;
-
using namespace std::placeholders;
-
-
int main(void)
-
{
-
void confun(int a, int b, int c,int d);
-
auto con = bind(confun,_2, 4,_1,_3);
-
con( 5, 6, 3);
-
}
-
void confun(int a,int b,int c,int d)
-
{
-
cout << "a=" << a << ends << "b=" << b << ends << "c=" << c << ends << "d=" << d << endl;
-
}
confun参数a 对应占位符 _2接受con第二个参数 6 ,b对应4,c对应占位符_1接受con第一个参数 5 ,d对应占位符_3,接受con第三个参数3
4、绑定引用参数
默认情况下,bind的那些不是占位符的参数被拷贝到bind返回的可调用对象中。但是,与lambda类似,有时对有些绑定的参数我们希望以引用方式传递,或是要绑定参数的类型无法拷贝,可以用ref(参数)
小细节:
class A
{
public:
int Func(int x, int y)
{
return x + y;
}
};
int main()
{
A a;
//bf2把一个类成员函数绑定了类对象,生成了一个像普通函数一样的新的可调用实体
auto bf2 = std::bind(&A::Func, a, std::placeholders::_1, std::placeholders::_2);
cout << bf2(10, 20);
system("pause");
return 0;
}