fork download
  1. #include <algorithm>
  2. #include <functional>
  3. #include <iostream>
  4. #include <string>
  5. #include <random>
  6.  
  7. template <typename T>
  8. struct functor
  9. {
  10. T data ;
  11.  
  12. functor(const T& t) : data(t) {}
  13.  
  14. void operator()() { std::cout << data << '\n' ; }
  15. };
  16.  
  17. struct random_functor
  18. {
  19. std::mt19937 engine ;
  20. std::uniform_int_distribution<int> dist ;
  21.  
  22. random_functor(int min, int max) : engine(std::random_device()()), dist(std::min(min,max), std::max(min,max)) {}
  23.  
  24. int operator()() { return dist(engine) ; }
  25. };
  26.  
  27. std::ostream& operator<<(std::ostream & os, random_functor& rf)
  28. {
  29. return os << rf() ;
  30. }
  31.  
  32. class myclass
  33. {
  34. public:
  35. myclass( std::function<void()> f = nullptr ) : _func(f) {}
  36. void setCallback( std::function<void()> f ) { _func = f ; }
  37.  
  38. void doCallback() const { _func(); }
  39.  
  40. private:
  41. std::function<void()> _func ;
  42. };
  43.  
  44. int main()
  45. {
  46. myclass obj ;
  47.  
  48. obj.setCallback(functor<std::string>("Hello, world!")) ;
  49. obj.doCallback() ;
  50.  
  51. obj.setCallback(functor<int>(42)) ;
  52. obj.doCallback() ;
  53.  
  54. obj.setCallback(functor<random_functor>(random_functor(-100, 100))) ;
  55. for ( unsigned i=0; i<10; ++i )
  56. obj.doCallback() ;
  57. }
  58.  
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
Hello, world!
42
1
-36
-57
-62
-7
96
-94
-81
-28
-68