C++ 回调函数示例:使用 std::function 通知调用者
假设有一个函数 do_something(),该函数需要在完成后调用一个回调函数来通知调用者。
#include <iostream>
#include <functional>
void do_something(std::function<void()> callback) {
// 做一些事情...
// 完成后调用回调函数
callback();
}
void callback_function() {
std::cout << '回调函数被调用了!' << std::endl;
}
int main() {
do_something(callback_function);
return 0;
}
在上面的代码中,我们定义了一个函数 do_something(),它接受一个 std::function<void()> 参数,这个参数代表回调函数。在函数执行完毕后,我们调用了这个回调函数来通知调用者。
我们还定义了一个 callback_function() 函数作为回调函数。在 main() 函数中,我们调用了 do_something(),并将 callback_function() 作为参数传递给它。
运行上面的代码,输出应该是:
回调函数被调用了!
原文地址: https://www.cveoy.top/t/topic/nW14 著作权归作者所有。请勿转载和采集!