C++ 如何使用forward_list::remove_if删除回调

C++ 如何使用forward_list::remove_if删除回调,c++,c++11,stl,C++,C++11,Stl,我试图在C++11中实现一个事件类。添加事件处理程序和触发事件效果很好,但从事件中删除处理程序时遇到问题。这就是我到目前为止所做的: #include <forward_list> #include <iostream> #include <functional> template<typename... Values> class Event { public: typedef void(Signature)(Values...);

我试图在C++11中实现一个事件类。添加事件处理程序和触发事件效果很好,但从事件中删除处理程序时遇到问题。这就是我到目前为止所做的:

#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方法使用的条件是错误的,但我看不出问题所在。当我调试代码时,这个条件总是真的,这不是我需要的。有人能帮忙吗?

直接的问题是你的类型不正确。它应该是签名*或类似的东西。但这并不能解决根本问题。例如,您可以添加不引用voidint、int函数的处理程序。不能使用运算符-=”删除这些对象。第二个直接的问题是目标返回指向存储函数对象的指针。在您的例子中,这是指向函数指针的指针。这些指针当然是不同的,您必须取消对指针的引用以比较函数指针。boost::signals2通过返回一个句柄对象来解决此问题,该句柄对象可用于删除处理程序:Stra,ge当我打印目标类型的返回值时,我始终得到nullptr。。。。