我有一个执行此操作的弹出系统(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;
}
答案 0 :(得分: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);
答案 1 :(得分:0)
您可以将选项与操作相关联,然后执行与单击的
相关联的操作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(); } }
});
}