Observer模式的C++包装器



C++新手。我有一个类,它有一个遵循观察者模式的监听器向量。监听器从一个抽象类继承,该抽象类定义了不同的方法,如on_start、on_stop、on_sach_event等。这些方法没有相同的签名

我想编写一个事件处理方法,并在适当的时候从中调用注册的侦听器,使用适当的方法并提供所需的参数。当然,我可以在循环中为每个侦听器调用适当的方法。但这不是DRY,代码很难遵循。

有可能用一个函数来包装我上面的调用吗?类似的东西

void notify_listeners(?);

哪里"代表我现在不知道的东西。notify_listeners((将使用适当的方法和参数调用每个注册的侦听器。我想从我的evens处理方法中这样称呼它:

if (some_event)
notify_listeners(on_start(some arguments)); // calls on_start for each listener
if (other_event)
notify_listeners(on_stop(some other arguments));

"on_start";以及";_停止";作为侦听器定义的公共方法在标头中。谢谢

您可以用这种方式编写函数:

template <typename ...Params, typename ...Args>
void notify_listeners(void (MyBase::*method)(Params...), const Args &... args)
{
for (MyBase *listener : all_listeners)
(listener->*method)(args...);
}

其中,MyBase是所有侦听器从中继承的类,它具有on_...方法。

然后这样称呼它:

foo.notify_liteners(&MyBase::on_start, 1, 2, 3);

最新更新