Can two functors be compared for equality?

Duk*_*uke 6 c++ functor c++11

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.
};
Run Code Online (Sandbox Code Playgroud)

And a method like this:

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

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

actionsEqual(&FSMAction::action1, &FSMAction::action1)
Run Code Online (Sandbox Code Playgroud)

But not for:

actionsEqual(&FSMAction::action1, &FSMAction::action2)
Run Code Online (Sandbox Code Playgroud)

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.)

Mic*_*kis 2

原始函数最终是一个指针。你可以把它从 中挖掘出来std::function ,然后std::function::target它只是与 的比较void*

  • 不,他们不是。成员函数很特别。您不能将成员函数指针强制转换为原始函数指针。 (7认同)
  • @NathanOliver `target()` 似乎也适用于成员指针:http://coliru.stacked-crooked.com/a/76e4e6a1e58c8d97 显然它返回一个指向存储的类型擦除对象的指针。 (2认同)