C++ 回调函数示例
简单示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include <functional> #include <iostream>
void print() { std::cout << "print()" << std::endl; }
void callback(std::function<void()> func) { std::cout << "Enter: callback()" << std::endl; func(); std::cout << "Leave: callback()" << std::endl; }
int main() { callback(print); system("pause"); }
|
输出:
Enter: callback()
print()
Leave: callback()
接下来我们把这两个函数放入类中实现,在调用的时候绑定函数名和其对应实例就可以按以上例子方法调用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| #include <functional> #include <iostream>
class operation { public: void print() { std::cout << "print()" << std::endl; } };
class controller { public: void callback(std::function<void()> func) { std::cout << "Enter: callback()" << std::endl; func(); std::cout << "Leave: callback()" << std::endl; } };
int main() { controller control; operation op; auto f = std::bind(&operation::print, &op); control.callback(f); system("pause"); }
|
现在我们把绑定函数对象的过程封装起来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <functional> #include <iostream>
class operation { public: auto get_print_function() { return std::bind(&operation::print, this); } void print() { std::cout << "print()" << std::endl; } };
class controller { public: void callback(std::function<void()> func) { std::cout << "Enter: callback()" << std::endl; func(); std::cout << "Leave: callback()" << std::endl; } };
int main() { controller control; operation op; control.callback(op.get_print_function()); system("pause"); }
|