fork download
  1. #include <list>
  2. #include <utility>
  3. #include <iostream>
  4.  
  5.  
  6. class Base
  7. {
  8. public:
  9. void doForAllDerived()
  10. {
  11. for (handlerList_t::const_iterator it = _registeredHandlers.begin(); it != _registeredHandlers.end(); ++it )
  12. (it->second)( it->first, 5 );
  13. }
  14.  
  15. protected:
  16. typedef void(*PrepFn)(Base*, int);
  17. typedef std::pair< Base *, PrepFn > handlerPair_t;
  18. void registerPrepFn( PrepFn fn, Base * instance )
  19. {
  20. _registeredHandlers.push_back( handlerPair_t( instance, fn ) );
  21. };
  22.  
  23. private:
  24. typedef std::list< handlerPair_t > handlerList_t;
  25. handlerList_t _registeredHandlers;
  26. };
  27.  
  28. class Derived : public Base
  29. {
  30. public:
  31. Derived() {
  32. registerPrepFn( &Derived::derivedPrepFn, this );
  33. };
  34.  
  35. protected:
  36. static void derivedPrepFn( Base* b_ptr, int n )
  37. {
  38. Derived * p_d = static_cast<Derived *>( b_ptr );
  39. p_d->realHandler( n );
  40. };
  41.  
  42. void realHandler( int n ) { std::cout << n << std::endl;};
  43.  
  44. };
  45.  
  46. int main() {
  47. Derived anInstance;
  48. anInstance.doForAllDerived();
  49. }
  50.  
Success #stdin #stdout 0.02s 2856KB
stdin
Standard input is empty
stdout
5