fork download
  1. #include <functional>
  2. #include <iostream>
  3. #include <array>
  4.  
  5. //We cannot touch this class
  6. class Button
  7. {
  8. public:
  9. virtual void onClick()
  10. {
  11.  
  12. }
  13. };
  14.  
  15. void click_button(Button& button)
  16. {
  17. button.onClick();
  18. }
  19.  
  20. class CustomButton: public Button
  21. {
  22. const std::function<void(void)> callback;
  23. public:
  24. CustomButton(std::function<void(void)> cb) : callback(std::move(cb)) {}
  25.  
  26. virtual void onClick() override
  27. {
  28. callback();
  29. }
  30. };
  31.  
  32. void meow() {std::cout << "meow";}
  33. void beep() {std::cout << "beep";}
  34. void clack() {std::cout << "clack";}
  35.  
  36. int main()
  37. {
  38. std::array<CustomButton, 3> buttons {{{meow}, {beep}, {clack}}};
  39. std::cout << "Which button do you want to press? (1-3)\n";
  40. int i;
  41. std::cin >> i;
  42. std::cout << "Button " << i << ' ';
  43. click_button(buttons[i-1]);
  44. std::cout << "'s\n";
  45. }
Success #stdin #stdout 0s 3464KB
stdin
1
stdout
Which button do you want to press? (1-3)
Button 1 meow's