Search code examples
c++c++11std-functionstdbind

Compare std::function created with std::bind


Here is a toy example

#include <iostream>
#include <functional>

struct Obj
{
  int x;

  int foo()
  {
    return 42;
  }
};

int main()
{
  Obj a, b;
  std::function<int()> f1 = std::bind(&Obj::foo, &a);
  std::function<int()> f2 = std::bind(&Obj::foo, &b);
  std::function<int()> f3 = std::bind(&Obj::foo, &a);
  std::function<int()> f4 = std::bind(&Obj::foo, &b);
}

How can I verify that f1 == f3 and f2 == f4, where the == comparator, here, means that both std::function objects correspond to the same method of the same object?


Solution

  • You don't.

    If you want == you'll have to write your own type erasing wrapper, possibly using std::function to store state.

    As std::bind does not support == and neither does lamba, you'll have to inject a custom function object that does support == to be type erased.

    None of these are easy. Alternative solutions, like registering binds with names, will be more practical.