在 C++ 中取消绑定 std::bind

Unbinding std::bind in c++

我有一些函数指针与其各自的 class 对象绑定:

ExampleClass EO;
std::function<void()> Example=std::bind(&ExampleClass::ExampleFunction, &EO);

但是,我想在稍后 'unbind' 这些,特别是确定每个“std::function”相关的特定 class。

auto Unbind(std::function<void()> &Example)->void
{
  //Find which object &Example is bound with (in this case EO/ExampleClass)
}

这样做的最佳方法是什么?

std::function 执行类型擦除。根据名称,它从接口中删除了真正的底层类型。

没有回头路了。

如果你想保留目标对象的类型,那么std::mem_fn可能就是你想要的:

http://en.cppreference.com/w/cpp/utility/functional/mem_fn

你不能用 function 对象来做。

一种可能性是构造一个包装器,在其中存储对方法和对象的引用。

像这样:

template<typename T, typename Fn>
struct MemberFunctionPointer {
  MemberFunctionPointer(T* ref, Fn fn) : m_ref(ref),
                                          m_method(fn) { }

  template<typename... Args>
  auto operator()(Args&&... args) {
    return (m_ref->*m_method)(std::forward<Args...>(args)...);
  }

  T* m_ref = nullptr;  // a reference (pointer) to the object instance
  Fn m_method = nullptr;  // a reference to the function method
};

注意:这只是一个划痕。您应该添加一个更复杂的界面。此外,用于创建 MemberFunctionPointer 对象的辅助函数也很有用。

您可以传递那种对象而不是简单的 function

struct Foo {
  void bar() {
    // something
  }
};

int main(int argc, char *argv[]) {
  Foo f;
  MemberFunctionPointer<Foo, decltype(&Foo::bar)> method(&f, &Foo::bar);

  method();  // call the method on the object f.

  assert(&f == method.get_obj_reference());
  return 0;
}