std::bind可以绑定成员函数,但绑定成员函数时有特殊的语法要求。
一、绑定成员函数的基本语法
当使用std::bind绑定非静态成员函数时,需要提供两个关键信息:
1.成员函数指针;
2.对象实例(用于提供this指针)
案例:
class Example{
public:
int add(int x,int y){
cout << "Example:add(int x,int y)" << endl;
return x + y;
}
};
void test(void){
// 绑定成员函数
Example ex;
auto f = bind(&Example::add,&ex,10,20); // 指针传递
cout << "f()" << f() << endl;
cout << endl;
}
二、绑定成员函数的原理
成员函数有一个隐藏的this参数,所以:
// 当你写:
ex.add(10, 20);
// 编译器实际上处理为:
Example::add(&ex, 10, 20);
因此,std::bind需要你显式提供这个this指针的等价物。
三、提供对象实例不同方式
方式一:通过指针(最常用)
// 绑定成员函数
Example ex;
auto f = bind(&Example::add,&ex,_1,_2); // 指针传递
cout << "指针传递f()" << f(10,20) << endl;
cout << endl;
方式二:通过引用(推荐)
auto f1 = bind(&Example::add,std::ref(ex),_1,_2); // 引用传递
cout << "引用传递f1()" << f(30,40) << endl;
cout << endl;
方式三:通过复制(创建副本)
auto f2 = bind(&Example::add,ex,_1,_2); // 值传递,创建副本
cout << "值传递/创建副本f2()" << f2(50,60) << endl;
cout << endl;
方式四:通过智能指针
四、绑定静态成员函数
静态成员函数不需要对象实例,因为静态成员函数没有this指针,绑定方式与普通函数相同。
class Math{
public:
static int area(int x , int y){
return x * y;
}
};
void test(void){
auto f = bind(&Math::area,3,4);
cout << "bind绑定静态成员函数与普通函数方式相同" << f() << endl;
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。