fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. namespace sf { using Event = int ; }
  5.  
  6. class event_callback
  7. {
  8. std::function< bool( const sf::Event& ) > func;
  9.  
  10. public:
  11. template< typename FN, typename... ADDITIONAL_ARGS >
  12. event_callback( FN f, ADDITIONAL_ARGS... additional_args )
  13. : func { std::bind( f, std::placeholders::_1, additional_args... ) } {}
  14.  
  15. bool run(const sf::Event& evt) { return func(evt); }
  16. };
  17.  
  18. struct A
  19. {
  20. bool mem_fun( const sf::Event& ) { return std::cout << "A::mem_fun\n" ; }
  21. bool mem_fun_with_more_args( sf::Event, int, char )
  22. { return std::cout << "A::mem_fun_with_more_args\n" ; }
  23. };
  24.  
  25. int free_fun( sf::Event e, A& a, double d )
  26. {
  27. // ...
  28. std::cout << "free_fun => " ;
  29. return a.mem_fun_with_more_args( e, d, 'H' ) ;
  30. }
  31.  
  32. bool logger( sf::Event ) { std::cout << "just log the event\n" ; return true ; }
  33.  
  34. int main()
  35. {
  36. A a ;
  37.  
  38. event_callback cb{ std::bind( &A::mem_fun, &a, std::placeholders::_1 ) } ;
  39. cb.run(30) ;
  40.  
  41. cb = std::bind( &A::mem_fun_with_more_args, &a, std::placeholders::_1, 78, 'D' ) ;
  42. cb.run(30) ;
  43.  
  44. cb = std::bind( free_fun, std::placeholders::_1, std::ref(a), 23.5 ) ;
  45. cb.run(30) ;
  46.  
  47. cb = [&a]( sf::Event x ) { std::cout << "closure => " ; return a.mem_fun(x) ; } ;
  48. cb.run(30) ;
  49.  
  50. cb = logger ;
  51. cb.run(30) ;
  52. }
  53.  
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
A::mem_fun
A::mem_fun_with_more_args
free_fun => A::mem_fun_with_more_args
closure => A::mem_fun
just log the event