我有一个这样做的弹出系统(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);
您可以将选择与操作相关联,然后执行与单击
关联的操作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(); } }
});
}