fork download
  1. #include <iostream>
  2.  
  3. struct Function
  4. {
  5. virtual ~Function() {}
  6. virtual void operator()() = 0;
  7. };
  8.  
  9. template <typename Class, typename ARG1>
  10. struct MemberFunction1 : public Function
  11. {
  12. typedef void (Class::*MEM_FUNC)(ARG1);
  13. explicit MemberFunction1(Class * obj, MEM_FUNC func, ARG1 arg1) : m_object(obj), m_func(func), m_arg1(arg1) {}
  14.  
  15. virtual void operator()()
  16. {
  17. (m_object->*m_func)(m_arg1);
  18. }
  19.  
  20. Class * m_object;
  21. MEM_FUNC m_func;
  22. ARG1 m_arg1;
  23. };
  24.  
  25. struct FunctionStorage
  26. {
  27. explicit FunctionStorage(Function * func) : m_func(func) {}
  28.  
  29. virtual ~FunctionStorage()
  30. {
  31. if (m_func)
  32. {
  33. delete m_func;
  34. m_func = 0;
  35. }
  36. }
  37.  
  38. void call() { (*m_func)(); }
  39. Function * m_func;
  40. };
  41.  
  42. struct MemberFunction : public FunctionStorage
  43. {
  44. template <typename Class, typename ARG1>
  45. MemberFunction(Class * obj, void (Class::*func)(ARG1), ARG1 arg1) : FunctionStorage(new MemberFunction1<Class, ARG1>(obj, func, arg1)) {}
  46. };
  47.  
  48.  
  49. class Foo
  50. {
  51. public:
  52. void funcWithParam(int value)
  53. {
  54. std::cout << "foo::funcWithParam(" << value << ")\n";
  55. }
  56. void funcWithParam(const char * msg)
  57. {
  58. std::cout << "foo::funcWithParam(" << msg << ")\n";
  59. }
  60. };
  61.  
  62. int main()
  63. {
  64. Foo f;
  65. MemberFunction(&f, &Foo::funcWithParam, 5).call();
  66. MemberFunction(&f, &Foo::funcWithParam, "hello").call();
  67. return 0;
  68. }
  69.  
Success #stdin #stdout 0.01s 2860KB
stdin
Standard input is empty
stdout
foo::funcWithParam(5)
foo::funcWithParam(hello)