如何使用 c++11 std::bind 绑定类中同名的成员函数之一
How to bind one of member functions of the same name in a class, with c++11 std::bind
class Test{
public:
int work(){
cout << "in work " << endl;
return 0;
}
void work(int x){
//cout << "x = " << x << endl;
cout << "in work..." << endl;
}
};
int main(){
Test test;
std::function<void()> f = std::bind(&Test::work, &test);
thread th(f);
th.join();
return 0;
}
如上面的代码,我想绑定一个类的成员函数void work(void)
(我们将其命名为Test(,但发生编译器错误,说无法确定使用哪个被覆盖的函数。
不能改变类测试,因为它属于一个库,如何实现我的目标?提前感谢!
为什么不完全跳过std::bind
并使用lambda?
auto fp = [&t]() { t.test()};
作为奖励,您的可执行文件大小会更小,并且您的编译器在适当的情况下更容易内联代码。
通过将其转换为正确的类型:
std::function<void()> f = std::bind( static_cast<int (Test::*)()>(&Test::work), &test);
在推导要绑定的模板参数时,编译器不在允许函数重载解析的上下文中 - 简单来说,它还没有那么远。
推导出第一个参数确实是成员函数指针的名称后,它发现有两个同名但不同类型的函数。
在这个阶段,它们都是同样有效的候选者(从模板参数推导的角度来看(,因此它是模棱两可的
静态强制转换消除了歧义,因为我们正在将编译器推到它必须推断模板类型的阶段之外 - 我们自己承担了模板类型推断的责任 - 通过在static_cast
中指定类型。
所以现在它所要做的就是过载解决。
#include <functional>
#include <thread>
#include <iostream>
using namespace std;
class Test{
public:
int work(){
cout << "in work " << endl;
return 0;
}
void work(int x){
//cout << "x = " << x << endl;
cout << "in work..." << endl;
}
};
int main(){
Test test;
// only overload resolution required here
auto fp = static_cast<int (Test::*)()>(&Test::work);
// type is now unambiguous and overload resolution is already done
std::function<void()> f = std::bind(fp, &test);
thread th(f);
th.join();
return 0;
}
试试这个(成员函数ptr(:
int main(){
Test test;
typedef int(Test:: *WKPtr)(void);
WKPtr p = &Test::work;
std::function<int()> f = std::bind(p, &test);
f();
return 0;
}
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法