Search code examples
c++c++11functor

Can two functors be compared for equality?


Is there a way for a method, which receives two functors as arguments, to find out if they are pointing to the same function? Specifically, having a struct like this:

struct FSMAction {
    void action1() const { std::cout << "Action1 called." << std::endl; }
    void action2() const { std::cout << "Action2 called." << std::endl; }
    void action3() const { std::cout << "Action3 called." << std::endl; }

private:
    // Maybe some object-specific stuff.
};

And a method like this:

bool actionsEqual(
    const std::function<void(const FSMAction&)>& action1, 
    const std::function<void(const FSMAction&)>& action2)
{
    // Some code.
}

Is there "some code" that will return true only for:

actionsEqual(&FSMAction::action1, &FSMAction::action1)

But not for:

actionsEqual(&FSMAction::action1, &FSMAction::action2)

Maybe this question doesn't make any sense (first clue would be that there seems to be nothing on the internet about it...). If so, could you give a hint, why, and if there are ways to accomplish something "similar"? (Basically, I'd like to have a set of callbacks with only "unique" items in the above-outlined sense.)


Solution

  • A raw function is eventually a pointer. You can dig it out of std::function with std::function::target and then it's simply a comparison of void*.