fork(1) download
  1.  
  2. #include <memory>
  3. #include <iostream>
  4. #include <functional>
  5.  
  6. struct A: std::enable_shared_from_this<A> {
  7.  
  8. template <typename... Args>
  9. std::function<void(Args...)> functor_from_this(void (A::*method)(Args...)) {
  10. return [=, obj = shared_from_this()](Args... args) {
  11. ((*obj).*method)(args...);
  12. };
  13. }
  14.  
  15. void foo(int) { std::cout << "foo" << '\n'; }
  16. void bar() { std::cout << "bar" << '\n'; }
  17. };
  18.  
  19. int main()
  20. {
  21. auto a = std::make_shared<A>();
  22.  
  23. auto f = a->functor_from_this(&A::foo);
  24. auto b = a->functor_from_this(&A::bar);
  25.  
  26. f(1);
  27. b();
  28. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
foo
bar