首页 > 解决方案 > 将函数名称传递给事件总线系统中的事件类

问题描述

我正在编写一个简单的事件总线系统来熟悉这个模型。我有一个 addEvent 函数,它接受一个事件名称(字符串)和一个函数。我无法建立我的活动课程。

// Event class to define our event
class Event
{
public:
    // function is some function that needs to be executed later
    Event(const string eventName, void * function)
    {
        msgEvent.first = event;
        msgEvent.second = function;
    }

    string getEvent(){
        return msgEvent;
    }
private:
    pair<string, void*> msgEvent;
};

因此,当我调用 addEvent("open", openFunction) 时,我想将此信息存储为事件的一部分。

我很难理解如何存储函数以及是否正确地将构造函数中的函数作为参数传递。

标签: c++

解决方案


您可以使用函数指针或std::function. void*肯定是不正确的。在任何情况下,您都需要知道您的函数具有什么签名。假设您的函数不接受任何输入并且不返回。然后,他们的签名是void()

然后,您可以使用以下代码:

#include<functional>
#include<string>
class Event
{
public:
    // function is some function that needs to be executed later
    Event(const std::string eventName, std::function<void()> functionName)
    {
        msgEvent.first = eventName;
        msgEvent.second = functionName;
    }

    std::string getEvent(){
        return msgEvent.first;
    }

    void execute() {
        msgEvent.second();
    }

private:
    std::pair< std::string, std::function<void()> > msgEvent; // why are you using
                                                              // std::pair here?
};

现在,你可以写

Event myEvent( "open", [](){ /* do something */ } );
myEvent.execute();

推荐阅读