C++ 回调函数示例
C++ 回调函数示例
简单示例
#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()
接下来我们把这两个函数放入类中实现,在调用的时候绑定函数名和其对应实例就可以按以上例子方法调用。
#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");
}
现在我们把绑定函数对象的过程封装起来
#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");
}