fork(2) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Foo{
  5. public:
  6. void bar(){
  7. cout << "Foo called\n";
  8. }
  9. };
  10.  
  11.  
  12. class Foo2{
  13. public:
  14. void bar2(){
  15. cout << "Foo2 called\n";
  16. }
  17. };
  18.  
  19. class Function{
  20. public:
  21. virtual void call()=0;
  22. };
  23.  
  24.  
  25. template<typename T>
  26. class TemplatedFunction : public Function{
  27. public:
  28. void (T::*m_fkt)();
  29. T* m_obj;
  30.  
  31. TemplatedFunction(T* obj, void (T::*fkt)()):m_fkt(fkt),m_obj(obj){}
  32.  
  33. void call(){
  34. (m_obj->*m_fkt)();
  35. }
  36. };
  37.  
  38. class EventHandler{
  39. public:
  40. Function* m_func=nullptr;
  41.  
  42. template<class T>
  43. void SetCallbackFunction(T* obj, void (T::*mem_fkt)()){
  44. if(m_func != nullptr)
  45. delete m_func;
  46. m_func = new TemplatedFunction<T>(obj,mem_fkt);
  47. }
  48.  
  49. void TestCallback(){
  50. if(m_func != nullptr)
  51. m_func->call();
  52. }
  53.  
  54. ~EventHandler(){
  55. if(m_func != nullptr)
  56. delete m_func;
  57. }
  58. };
  59.  
  60. int main() {
  61. EventHandler eh;
  62. Foo foo;
  63. Foo2 foo2;
  64. eh.SetCallbackFunction(&foo, &Foo::bar);
  65. eh.TestCallback();
  66. eh.SetCallbackFunction(&foo2, &Foo2::bar2);
  67. eh.TestCallback();
  68. return 0;
  69. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
Foo called
Foo2 called