Comparing std::functions for equality?

Viewed 27824

How can I compare two C++11 std::functions with operator==, and return true if both of said functions refer to the same function pointer?

6 Answers

What about comparing two shared_ptr?

using MessageFilter = std::function<void(const int msgID)>;

static void onMessageReceived(const int msgID)
{
    std::cout << "msg id => " << msgID << std::endl;
}

static void someFunc()
{
    auto filter = std::make_shared<MessageFilter>(&onMessageReceived);

    if (filter && *filter)
    {
        (*filter)(1234);
    }
}

As you can see, 'filter' is a shared_ptr, so it is easy to compare with another.

Related