fork download
  1. #include <functional>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. enum System { SYS_A, SYS_B, SYS_C };
  6.  
  7. class Command {
  8. public:
  9. typedef std::function<void()> FuncType;
  10.  
  11. Command(FuncType func, std::initializer_list<System> requirements)
  12. :func_(func), requirements_(requirements) { }
  13.  
  14. void operator()() {
  15. std::cout << "Executing Command:" << std::endl;
  16. for ( System s : requirements_ )
  17. std::cout << " REQUIRES " << static_cast<int>(s) << std::endl;
  18. func_();
  19. }
  20.  
  21. private:
  22. FuncType func_;
  23. std::vector<System> requirements_;
  24. };
  25.  
  26. class Scheduler {
  27. public:
  28. void add(Command c) {
  29. c();
  30. }
  31. };
  32.  
  33. class Robot {
  34. public:
  35. Robot()
  36. :do_something_ (std::bind(&Robot::do_something, this), {SYS_A, SYS_B}),
  37. do_another_thing_(std::bind(&Robot::do_another_thing, this), {SYS_A, SYS_C}) { }
  38.  
  39. void runRobot() {
  40. s_.add(do_something_);
  41. s_.add(do_another_thing_);
  42. }
  43.  
  44. private:
  45. void do_first_thing() { std::cout << " FIRST THING!" << std::endl; }
  46. void do_second_thing() { std::cout << " SECOND THING!" << std::endl; }
  47. void do_third_thing() { std::cout << " THIRD THING!" << std::endl; }
  48.  
  49. void do_something() { do_first_thing(); do_second_thing(); }
  50. void do_another_thing() { do_first_thing(); do_third_thing(); }
  51.  
  52. Command do_something_;
  53. Command do_another_thing_;
  54. Scheduler s_;
  55. };
  56.  
  57. int main(int, char**) {
  58. Robot().runRobot();
  59. }
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
Executing Command:
   REQUIRES 0
   REQUIRES 1
   FIRST THING!
   SECOND THING!
Executing Command:
   REQUIRES 0
   REQUIRES 2
   FIRST THING!
   THIRD THING!