gpt4 book ai didi

c++ - C++ 中的 EventEmitter 类 : Listener and Emitter

转载 作者:行者123 更新时间:2023-12-03 12:51:00 24 4
gpt4 key购买 nike

我正在尝试实现一个类,该类允许监听某些事件,并且当这些事件发出时,它们会收到通知。

所以我想到使用仿函数,

 class MyFunctor {
public:
virtual void emit() {}
vitual void compare() {}
};

class MyFunctorSpecial : public MyFunctor {
void (*)() ab;
public:
MyFunctorSpecial(void (*a)()) : ab(a) {}
void emit() { ab(); }
};
class EventEmitter {
std::map<std::string, std::vector<MyFunctor> > eventMap;
public:
void On(const std::string &, const MyFunctor &) {
// add to the map
}

void Emit(const std::string & eventName) {
// emit the event
// for all listeners in the vector for this event-name
// call the emit of them.
}
};

EventEmitter emitter;
// some function - abc()
MyFunctorSpecial funct(abc);
emitter.On("hello", funct);
emitter.Emit("hello");

但现在我想将参数传递给听众。喜欢

 emitter.Emit("hello", 45, false);

我认为这些关于各种参数的数据类型的信息在编译时可用于Emit()。我可以使用该信息来实现它吗,使用模板或任何东西。

这个问题是否有另一种模式?我怎样才能做到这一点?

最佳答案

您的问题的常见设计模式称为 Observer Design-Pattern .

enter image description here

你所谓的“仿函数”不是仿函数。如果是这样,它们就会实现一个operator()方法,并且可以像函数一样被调用(因此得名仿函数)。你的不是。

例如,这是一个仿函数:(注意operator())

class MyFunctor 
{
public:
void operator()(){};
};

关于c++ - C++ 中的 EventEmitter 类 : Listener and Emitter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20739486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com