相关疑难解决方法(0)

std :: function/bind就像没有标准C++库的type-erasure一样

我正在基于发布/订阅模式在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)

c++ pointers type-erasure c++11

6
推荐指数
1
解决办法
1487
查看次数

标签 统计

c++ ×1

c++11 ×1

pointers ×1

type-erasure ×1