fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. class Button
  5. {
  6. public:
  7. // Typedef of the event function signature
  8. typedef std::function<void(Button*)> EventCallback;
  9.  
  10. Button() : onClick(nullptr) {}
  11.  
  12. // Set the function to call
  13. void SetOnClick(EventCallback func) { onClick = func; }
  14. // Call the function if exists
  15. void OnClick() {
  16. if (onClick)
  17. onClick(this);
  18. }
  19.  
  20. private:
  21. // This stores the function pointer for the button
  22. EventCallback onClick;
  23. };
  24.  
  25. // just some example function that has the same signature as Button::EventCallback
  26. void MyEventFunc(Button* button)
  27. {
  28. std::cout << "Triggered" << std::endl;
  29. }
  30.  
  31. int main() {
  32. Button button;
  33. button.SetOnClick(&MyEventFunc);
  34. button.OnClick();
  35. return 0;
  36. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
Triggered