在编写C++项目时,经常需要将类的某个成员函数作为回调函数使用,这里总结两个方法:
1.使用lambda函数,将类函数封装后使用,代码示例:
#include<funtional> #include<memory> class A { public: A(std::function<int(int)> callback):m_callback(callback) { } int Run(int a) { return m_callback(a); } private: std::functin<int(int)> m_callback; }; class B { public: B() { m_a = std::make_shared<A>([&](int a){this->callback(a);}); } int callback(int a){ std::cout << a << std::endl; } private: std::shared_ptr<A> m_a; };
2.使用std::bind,将类函数封装后使用,代码示例:
#include<funtional> #include<memory> class A { public: A(std::function<int(int)> callback):m_callback(callback) { } int Run(int a) { return m_callback(a); } private: std::functin<int(int)> m_callback; }; class B { public: B() { m_a = std::make_shared<A>(std::bind(&B::callback, this, std::placeholders::_1)); } int callback(int a){ std::cout << a << std::endl; } private: std::shared_ptr<A> m_a; };
标签:std,include,函数,示例,int,callback,回调 From: https://www.cnblogs.com/sheldon1990/p/18159548