fork(1) download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. template<typename F, typename C>
  5. auto smart_bind(F f, C* c)
  6. {
  7. return [c, f](auto&&... args) { return (c->*f)(std::forward<decltype(args)>(args)...); };
  8. }
  9.  
  10. struct Foo
  11. {
  12. int bar(int i, float f, bool b)
  13. {
  14. return b ? i : f;
  15. }
  16. double sum(double x, double y)
  17. {
  18. return x + y;
  19. }
  20. void print(int x)
  21. {
  22. std::cout << x << std::endl;
  23. }
  24. };
  25.  
  26. int main()
  27. {
  28. Foo object;
  29. std::function<int(int, float, bool)> f1 = smart_bind(&Foo::bar, &object);
  30. std::function<double(double, double)> f2 = smart_bind(&Foo::sum, &object);
  31. std::function<void(int)> f3 = smart_bind(&Foo::print, &object);
  32.  
  33. std::cout << f1(100, 150.32, true) << std::endl;
  34. std::cout << f2(1.0, 2.0) << std::endl;
  35. f3(42);
  36. }
  37.  
Success #stdin #stdout 0s 4484KB
stdin
Standard input is empty
stdout
100
3
42