C++ function callback for class function - Stack Overflow

admin2025-03-19  1

I have below snipped code works properly. But in my opinion it shouldn't work.

#include <functional>

template <class T> void run(std::function<void(T *)> fun, T *obj) { fun(obj); }

struct Foo {
  void bar() {}
};

int main() {
  Foo foo;
  std::function<void(Foo *)> fun = &Foo::bar;

  run(fun, &foo);                     // works
}
  1. The bar() function is not compatible with the expected blueprint. bar() function accepts no parameter but std::functional accepts T *.
  2. fun variable is defined only &Foo::bar. How compiler knows, it is function of foo object?
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1742375141a210397.html

最新回复(0)