fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. #include <sstream>
  5.  
  6. typedef void (*FooPointer) ( ) ;
  7. std :: map < std :: string , FooPointer > fooCollection ;
  8.  
  9.  
  10. void foo1 ( ) {
  11. std :: cout << "Call foo1 ( )" << std ::endl ;
  12. }
  13.  
  14. void foo2 ( ) {
  15. std :: cout << "Call foo2 ( )" << std ::endl ;
  16. }
  17.  
  18.  
  19. int main() {
  20. //Добавляем указатели на функции в контейнер
  21. fooCollection [ "foo1" ] = foo1 ;
  22. fooCollection [ "foo2" ] = foo2 ;
  23.  
  24. size_t num ;
  25. std :: cout << "Enter number" << std :: endl ;
  26. std :: cin >> num ;
  27.  
  28. //Формируем имя
  29. std :: ostringstream ss ;
  30. ss << "foo" ;
  31. ss << num ;
  32.  
  33. //Вызываем функцию, если она найдена.
  34. std :: map < std :: string , FooPointer > :: iterator it = fooCollection.find ( ss.str ( ) ) ; //Ищем функцию по имени
  35. if ( it != fooCollection.end ( ) )
  36. (*it).second ( ) ; //Вызываем функцию по указателю
  37. }
Success #stdin #stdout 0s 3436KB
stdin
2
stdout
Enter number
Call foo2 ( )