【问题标题】:C++ lambda/callback popup?C++ lambda/回调弹出窗口?
【发布时间】:2017-12-20 08:10:54
【问题描述】:

我有一个弹出系统 (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/callback 来安排它,如下所示。这样该功能“保留”并且可以在按下按钮时激活(返回一个值)。

谢谢!

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

【问题讨论】:

  • 你能详细说明elsewhere in code吗?听起来你想用延续进行编程。如描述here for boost::future
  • 这对于您使用的 GUI 框架非常具体 - e。 G。使用 QT,您可以将按钮的信号连接到您编程的适当插槽,使用 wxWidgets,您仍然可以直接处理按钮按下,注册适当的命令事件并获取按下按钮的 id,...
  • 我使用原生 c++ 制作了自己的 gui 框架。或者实际上通常是 c :) 所以我正在寻找一个使用 c++ 的通用解决方案。

标签: c++ lambda


【解决方案1】:

你可以给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);

【讨论】:

    【解决方案2】:

    您可以将选择与动作相关联,然后执行与点击相关联的动作

    using PopupActions = std::map<std::string, std::function<void()>>;
    
    void callPopup(int id, std::string prompt, PopupActions actions)
    {
        for (auto & pair : actions)
            // create button with text from pair.first and on-click from pair.second
        // show buttons
    }
    
    if (timeToEat())
       callPopup(ID_4, "What to eat?", { 
           { "Cake!", [this]{ eatCake(); } }
           { "Cookies!", [this]{ eatCookies(); } }
       });
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 2012-07-17
      相关资源
      最近更新 更多