我试图在C ++ 11中实现Event
类。添加事件处理程序并触发事件很有效但我无法从事件中删除处理程序。这就是我到目前为止所做的:
#include <forward_list>
#include <iostream>
#include <functional>
template<typename... Values>
class Event
{
public:
typedef void(Signature)(Values...);
typedef std::function<Signature> Handler;
public:
void operator () (Values... values) {
for (const auto& handler: handlers) {
handler(values...);
}
}
Event& operator += (const Handler& handler) {
handlers.push_front(handler);
return *this;
}
Event& operator -= (const Handler& handler) {
handlers.remove_if([&](const Handler& entry) {
return entry.template target<Signature>() == handler.template target<Signature>();
});
return *this;
}
private:
std::forward_list<Handler> handlers;
};
void handler1(int a, int b) {
std::cout << "Event handler 1 " << std::endl;
}
void handler2(int i, int a) {
std::cout << "Event handler 2 " << std::endl;
}
int main(void) {
Event<int, int> event;
// Add two event handlers
event += handler1;
event += handler2;
// Both event handlers should be called (Works)
event(1, 2);
// Remove one of the event handlers
event -= handler2;
// The other one should still be called (Fails!)
event(1, 2);
}
我的问题是减法运算符总是删除所有事件处理程序,而不仅仅是指定的事件处理程序。我非常确定我使用remove_if
方法的条件是错误的,但我没有看到问题。当我调试代码时,这个条件总是true
,这不是我需要的。有人可以帮忙吗?