C++ lambda/回调弹出窗口?

标签 c++ lambda

我有一个执行此操作的弹出系统 (GUI):

// creates popup with two possible answer-buttons
if (timeToEat())
  callPopup(ID_4, "What to eat?", "Cake", "Cookies!"); 

//elsewhere in code i check for key presses
if (popupAnswered(ID_4,0)) // clicked first button in popup
  eatCake();

if (popupAnswered(ID_4,1)) // clicked second button in popup
  eatCookiesDamnit();

我可以使用某种 lambda/回调来安排它,如下所示。这样该功能“保留”并且可以在按下按钮时激活(返回值)。

谢谢!

if (timeToEat())
   callPopup("What to eat?", "Cake", "Cookies!"){
       <return was 0 :>  eatCake(); break;
       <return was 1 :>  eatCookies(); break;
}

最佳答案

您可以向 callPopup 添加一个延续参数:

void callPopup(int id, std::function<void(int)> f)
{
    if (something)
        f(0);
    else
        f(1);
}

//...

callPopup(ID_4, [](int x) { if (x == 0) eatCake(); });

或者你可以添加另一个函数层并使用返回值:

std::function<void(std::function<void(int)>)> 
callPopup(int id)
{
        return [](std::function<void(int)> f) { f(something ? 0 : 1); }
}

// ...
callPopup(ID_4)([](int x) { if (x == 0) ... ;});
// or
void popupHandler(int);
auto popupResult = callPopup(ID_4);
// ...
popupResult(popupHandler);

关于C++ lambda/回调弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47901447/

相关文章:

c++ - 使用 C++ 解析 robots.txt 文件

c++ - 堆栈溢出与 std::make_unique 但不是与原始指针

c++ - 用列表中的每个元素调用 C++ 成员函数?

c++ - 如何使用 lambda 来 boost asio 异步完成处理程序

c# - Linq.Expression TryCatch - 将异常传递给 Catch block ?

c++ - 在 C++11 中重新绑定(bind) lambda...这可能吗?

c# - Lambda 按参数排序性能

c++ - 为什么我的 C++ 程序在将 lambda 转换为函数指针时崩溃

c++ - 将 LTO 与 arm-none-eabi 和 newlib-nano 结合使用

c++ - 使用来自 cygwin 的 g++ C++ 编译器