In the old C ++, the pointer worked only on ordinary functions, and functions - members of the class could not be assigned. Has anything new appeared in C ++ 11 for implementing callback functions?
1 answer
Yes. A std::function was introduced that allows you to pass not only a function for a callback, but generally any functional object (pointers to a class method, lambdas, bindings (see std::bind ), etc.). An example of using this class is shown below:
#include <iostream> #include <string> #include <functional> typedef std::function<int(std::string)> CALLBACK; class Foo { private: int x = 13; public: int callback(std::string str) { std::cout << "callback: " << str << " " << x << std::endl; return 17; } }; class A { private: CALLBACK m_callback; public: void set_callback(CALLBACK callback) { m_callback = callback; } void call_callback() { // проверка на жизнеспособность callback-a m_callback("privet"); } }; int main() { int y = 0; Foo* ptr = new Foo(); A* a = new A(); a->set_callback(std::bind(&Foo::callback, ptr, std::placeholders::_1)); //delete ptr; // контроля за жизню объекта нету a->call_callback(); } |
std::function<...>, then it is quite possible for a member function . - VladD