fork download
  1. #include <map>
  2. #include <cstdlib>
  3. #include <iostream>
  4.  
  5. class Foo
  6. {
  7. public:
  8. void update( )
  9. {
  10. std::cout << "Foo::update()" << std::endl;
  11. }
  12. };
  13.  
  14. class Bar
  15. {
  16. public:
  17. void update( )
  18. {
  19. std::cout << "Bar::update()" << std::endl;
  20. }
  21. };
  22.  
  23. class Container
  24. {
  25. public:
  26. typedef void (Container::*updateMethod)();
  27. typedef std::map<std::string , updateMethod> UpdateMethodMap;
  28.  
  29. static const UpdateMethodMap m_updateMethod;
  30. static UpdateMethodMap initializeUpdateMethodMap();
  31. static updateMethod getUpdateMethod( const std::string attributeName );
  32.  
  33. void update( const std::string name )
  34. {
  35. updateMethod updater = getUpdateMethod( name );
  36. if( updater )
  37. {
  38. (this->*updater)();
  39. }
  40. }
  41.  
  42. void updateFoo()
  43. {
  44. std::cout << "Container::updateFoo() -> ";
  45. m_foo.update();
  46. }
  47.  
  48. void updateBar()
  49. {
  50. std::cout << "Container::updateBar() -> ";
  51. m_bar.update();
  52. }
  53.  
  54. private:
  55. Foo m_foo;
  56. Bar m_bar;
  57. };
  58.  
  59. const Container::UpdateMethodMap Container::m_updateMethod = Container::initializeUpdateMethodMap();
  60.  
  61. /////////////////////////////////////////////////////////////////////////////
  62.  
  63. Container::UpdateMethodMap Container::initializeUpdateMethodMap()
  64. {
  65. Container::UpdateMethodMap updateMethodMap;
  66.  
  67. updateMethodMap["foo"] = &Container::updateFoo;
  68. updateMethodMap["bar"] = &Container::updateBar;
  69.  
  70. return updateMethodMap;
  71. }
  72.  
  73. //////////////////////////////////////////////////////////////////////
  74.  
  75. Container::updateMethod Container::getUpdateMethod( const std::string name )
  76. {
  77. UpdateMethodMap::const_iterator updateMethodMapItx = m_updateMethod.find( name );
  78.  
  79. if( updateMethodMapItx == m_updateMethod.end() )
  80. {
  81. return NULL;
  82. }
  83.  
  84. return updateMethodMapItx->second;
  85. }
  86.  
  87. /////////////////////////////////////////////////////////////////////////////
  88.  
  89. int main()
  90. {
  91. Container c;
  92. c.update( "foo" );
  93. c.update( "bar" );
  94.  
  95. return EXIT_SUCCESS;
  96. }
  97.  
  98. //////////////////////////////////////////////////////////////////////
  99.  
Success #stdin #stdout 0.02s 2864KB
stdin
Standard input is empty
stdout
Container::updateFoo() -> Foo::update()
Container::updateBar() -> Bar::update()