fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4. using namespace std;
  5.  
  6. //************* Definitions
  7. class OtherClass;
  8.  
  9. class Command {
  10. public:
  11. virtual void execute() = 0;
  12. virtual ~Command();
  13. };
  14. class CommandOtherClass : public Command {
  15. OtherClass *target;
  16. void (OtherClass::*f)();
  17. public:
  18. CommandOtherClass (void (OtherClass::*fct)(), OtherClass*t);
  19. void execute() override;
  20. };
  21. class CommandAdHoc : public Command {
  22. public:
  23. void execute() override;
  24. };
  25. class SomeClass {
  26. public:
  27. static std::vector<unique_ptr<Command>> UpdateFuncs;
  28. static void executeAll();
  29. };
  30.  
  31. class OtherClass{
  32. private:
  33. void Update();
  34. public:
  35. OtherClass();
  36. };
  37.  
  38. //*************** Implementation
  39.  
  40. std::vector<unique_ptr<Command>> SomeClass::UpdateFuncs;
  41. Command::~Command() {}
  42. CommandOtherClass::CommandOtherClass (void (OtherClass::*fct)(), OtherClass*t)
  43. : f(fct),target(t)
  44. {
  45. }
  46. void CommandOtherClass::execute() {
  47. (target->*f)();
  48. }
  49. void CommandAdHoc::execute() {
  50. cout<<"Taht's all folks :-) !"<<endl;
  51. }
  52.  
  53. void SomeClass::executeAll() {
  54. for (auto &x:UpdateFuncs)
  55. x->execute();
  56. }
  57. OtherClass::OtherClass() {
  58. SomeClass::UpdateFuncs.push_back(make_unique<CommandOtherClass>(&OtherClass::Update, this));
  59. }
  60. void OtherClass::Update() {
  61. cout << "Hello, world, said by "<<this<<endl;
  62. }
  63.  
  64. int main() {
  65. OtherClass a,b;
  66. SomeClass::UpdateFuncs.push_back(make_unique<CommandAdHoc>());
  67.  
  68. SomeClass::executeAll();
  69. return 0;
  70. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Hello, world, said by 0x7ffd88f8ed5e
Hello, world, said by 0x7ffd88f8ed5f
Taht's all folks :-) !