C++ 在C++11之后,引入了functional模块。利用该模块我们可以实现一个通用的回调函数接口,既支持传统的全局函数、静态函数,又支持类的成员函数。
代码如下:
#include <functional>
class A
{
public:
A();
~A();
void SetCall(const std::function<void (int)> & func){ m_func = func; }
private:
void run()
{
m_func(123);
}
//可以将这个理解成回调函数的函数指针
std::function<void(int)> m_func;
};
class B
{
public:
B();
~B();
void functionB(int value)
{
cout << "functionB:" << value << endl;
}
};
void functionC(int value)
{
cout << "functionB:" << value << endl;
}
int main(int argc, char** argv)
{
B b;
A a;
a.SetCall(std::bind(&B::functionB, &b, std::placeholders::_1)); //将类成员函数作为回调
a.SetCall(functionC); //将普通函数作为回调
}