我正在基于发布/订阅模式在C++ 11中开发一个简单的事件驱动的应用程序.类具有onWhateverEvent()由事件循环调用的一个或多个方法(控制反转).由于应用程序实际上是一个固件,其中代码大小至关重要且灵活性不是高优先级,'subscribe'部分是一个带有事件ID和相关处理程序的简单表.
这是一个非常简化的想法代码:
#include <functional>
enum Events {
EV_TIMER_TICK,
EV_BUTTON_PRESSED
};
struct Button {
void onTick(int event) { /* publish EV_BUTTON_PRESSED */ }
};
struct Menu {
void onButtonPressed(int event) { /* publish EV_SOMETHING_ELSE */ }
};
Button button1;
Button button2;
Menu mainMenu;
std::pair<int, std::function<void(int)>> dispatchTable[] = {
{EV_TIMER_TICK, std::bind(&Button::onTick, &button1, std::placeholders::_1) },
{EV_TIMER_TICK, std::bind(&Button::onTick, &button2, std::placeholders::_1) },
{EV_BUTTON_PRESSED, std::bind(&Menu::onButtonPressed, &mainMenu, std::placeholders::_1) }
};
int main(void)
{
while(1) {
int event = EV_TIMER_TICK; // msgQueue.getEventBlocking();
for (auto& a …Run Code Online (Sandbox Code Playgroud)