C++ 使用lambda表达式作为函数参数
1. 使用模板参数实现
#include <iostream>
#include <string>
#include <unistd.h>
volatile bool g_is_running = true;
volatile bool g_is_idle = false;
template <typename T, typename F>
int32_t EventLoop(const T& do_func, const F& do_idle) {
while (g_is_running)
{
if (!g_is_idle)
{
int32_t ec = do_func();
if (ec != 0)
{
break;
}
}
else
{
do_idle();
}
}
g_is_running = false;
return 0;
}
int main(int argc, char ** argv) {
std::cout << "Hello, World!" << std::endl;
std::string language = "Rust";
auto do_biz = [&]() {
std::cout << "Welcome to " << language << std::endl;
sleep(1);
return 0;
};
auto do_idle = []() {
usleep(1);
};
return EventLoop(do_biz, do_idle);
}
2. 使用std::function方式实现
#include <iostream>
#include <string>
#include <unistd.h>
#include <functional>
volatile bool g_is_running = true;
volatile bool g_is_idle = false;
int32_t EventLoop(const std::function<int(void)>& do_func, const std::function<int(void)>& do_idle) {
while (g_is_running)
{
if (!g_is_idle)
{
int32_t ec = do_func();
if (ec != 0)
{
break;
}
}
else
{
do_idle();
}
}
g_is_running = false;
return 0;
}
int main(int argc, char ** argv) {
std::cout << "Hello, World!" << std::endl;
std::string language = "Rust";
auto do_biz = [&]() {
std::cout << "Welcome to " << language << std::endl;
sleep(1);
return 0;
};
auto do_idle = []() {
usleep(1);
return 0;
};
return EventLoop(do_biz, do_idle);
}