fork download
  1. #include <iostream>
  2. #include <deque>
  3.  
  4. struct Foo {
  5. bool memberFunc() { std::cout << "memberFunc of Foo called." << std::endl; return true; }
  6. };
  7.  
  8. struct Bar {
  9. bool memberFunc() { std::cout << "memberFunc of Bar called." << std::endl; return true; }
  10. };
  11.  
  12. struct func_base {
  13. virtual ~func_base() {};
  14. virtual bool operator()() const = 0;
  15. };
  16.  
  17. template <typename C>
  18. class func_wrapper : public func_base {
  19. public:
  20. typedef bool (C::*member_func_ptr_t)();
  21. func_wrapper(member_func_ptr_t func_ptr, C* instance_ptr) : m_func_ptr(func_ptr), m_instance_ptr(instance_ptr) {}
  22. bool operator()() const { return (m_instance_ptr->*m_func_ptr)(); }
  23. private:
  24. member_func_ptr_t m_func_ptr;
  25. C* m_instance_ptr;
  26. };
  27.  
  28. /* This function returns a pointer to dynamically *
  29.  * allocated memory and it is thus the callers *
  30.  * responsibility to deallocate the memory!! */
  31. template <typename C>
  32. func_base* make_wrapper(bool (C::*func_ptr)(), C* instance_ptr) {
  33. return new func_wrapper<C>(func_ptr, instance_ptr);
  34. }
  35.  
  36. int main() {
  37. Foo foo;
  38. Bar bar;
  39.  
  40. std::deque<func_base*> d;
  41.  
  42. d.push_back(make_wrapper(&Foo::memberFunc, &foo));
  43. d.push_back(make_wrapper(&Bar::memberFunc, &bar));
  44.  
  45. for (std::deque<func_base*>::iterator it = d.begin(); it != d.end(); ++it) {
  46. (**it)();
  47. }
  48.  
  49. for (std::deque<func_base*>::iterator it = d.begin(); it != d.end(); ++it) {
  50. delete *it;
  51. }
  52. }
Success #stdin #stdout 0s 2864KB
stdin
Standard input is empty
stdout
memberFunc of Foo called.
memberFunc of Bar called.