std::function
Callbacks are usually implemented through function pointers, function objects (functors), Lambda expressions, or .
1. Function pointer implements callback
This method of implementing callbacks is easier to remember. Just remember to pass the function as a parameter to the method and call the method in the method.
#include <iostream>
// 回调函数类型
typedef void (*CallbackFunction)(int);
// 使用回调函数的函数
void performCallback(int value, CallbackFunction callback) {
// 执行某些操作
std::cout << "Performing operation with value: " << value << std::endl;
// 调用回调函数
callback(value * 2);
}
// 回调函数
void callbackFunction(int value) {
std::cout << "Callback executed with value: " << value << std::endl;
}
int main() {
performCallback(5, callbackFunction);
return 0;
}
2. Function object (functor) implements callback
#include <iostream>
// 仿函数类
class CallbackClass {
public:
void operator()(int value) const {
std::cout << "Callback executed with value: " << value << std::endl;
}
};
// 使用回调函数对象的函数
void performCallback(int value, const CallbackClass& callback) {
// 执行某些操作
std::cout << "Performing operation with value: " << value << std::endl;
// 调用回调函数对象
callback(value * 2);
}
int main() {
CallbackClass callbackObj;
performCallback(5, callbackObj);
return 0;
}
3. Lambda expression implements callback
#include <iostream>
// 使用回调Lambda的函数
void performCallback(int value, const std::function<void(int)>& callback) {
// 执行某些操作
std::cout << "Performing operation with value: " << value << std::endl;
// 调用回调Lambda
callback(value * 2);
}
int main() {
// 定义并传递Lambda作为回调
performCallback(5, [](int value) {
std::cout << "Callback executed with value: " << value << std::endl;
});
return 0;
}
Recommended reading
C++ std::tr1::function and std::tr1::bind template class introduction, qt test-CSDN blog