c++ - 将函数名称传递给事件总线系统中的事件类
问题描述
我正在编写一个简单的事件总线系统来熟悉这个模型。我有一个 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) 时,我想将此信息存储为事件的一部分。
我很难理解如何存储函数以及是否正确地将构造函数中的函数作为参数传递。
解决方案
您可以使用函数指针或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();
推荐阅读
- r - 为新创建的因子组创建一个新列分组数字 (num)
- winforms - 如果主窗体或它所在的任何用户控件被移动或调整大小,则更改窗体位置
- angular - 在父视图中渲染 elementReference
- spring-boot - 使用 HttpURLConnection 使用 Mockito 进行单元测试
- c++ - 查询c++中函数的默认返回类型
- c - 可以打开读取传感器数据
- apache-spark - 如何以追加模式将“所有字符串”数据帧写入 Spark JDBC 到具有 int 和 varchar 列的目标表
- email - 预期响应代码 250,但得到代码“550”,消息“550 5.7.1 Relaying denied”
- android - E/ConstraintSet:transitionEasing 语法错误语法:transitionEasing="cubic(1.0,0.5,0.0,0.6)" 或 [标准、加速、减速、线性]
- html - 你能用 CSS 从图标中删除空白背景吗?