std::bind使用
1) std::bind绑定类的成员函数
#include <iostream>
#include <functional>
class simulate {
public:
simulate(int val):
num(val)
{
}
simulate()
{
}
virtual ~simulate() {}
void func(int a, int b) {
std::cout << "a=" << a << " b=" << b << " privateNum=" << num << std::endl;
}
private:
int num;
};
class inter {
public:
inter() {}
virtual ~inter() {}
void setFucn(std::function<void(int, int)> func)//设置函数指针
{
mFunc = func;
}
void callFucn(int a, int b)
{
mFunc(a, b);
}
private:
std::function<void(int, int)> mFunc = nullptr;//函数指针
};
int main()
{
std::cout << "Hello World!\n";
simulate simuObj(13);
inter interObj;
//output: a=5 b=6 privateNum=13
interObj.setFucn(std::bind(&simulate::func,simuObj ,5,6));//std::bind返回了一个std::function
//output: a=55 b=66 privateNum=13
//interObj.setFucn(std::bind(&simulate::func, simuObj, std::placeholders::_1, std::placeholders::_2));
//output: a=66 b=55 privateNum=13
//interObj.setFucn(std::bind(&simulate::func, simuObj, std::placeholders::_2, std::placeholders::_1));
interObj.callFucn(55, 66);
}
2) std::bind技术内幕
https://www.cnblogs.com/xusd-null/p/3698969.html
https://www.cnblogs.com/qicosmos/p/3723388.html
bind类包含一个函数指针,用于保存一个函数;bind类重载了operator()。