fork(2) download
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4.  
  5. typedef void(*FUNCPTR)(double*, int); // our typedef
  6. std::map<std::string, FUNCPTR> func_map;
  7.  
  8. // some functions
  9. void f1(double*, int) {std::cout << "f1" << std::endl;}
  10. void f2(double*, int) {std::cout << "f2" << std::endl;}
  11.  
  12. // call them via an invoking function
  13. void myMainFit(const std::string& which, double* ptr, int val)
  14. {
  15. if (func_map.find(which) != func_map.end()) // indeed the function was added
  16. func_map[which](ptr, val);
  17. else
  18. {
  19. std::cerr << "Function \"" << which << "\" is not in the map!\n";
  20. return; // or throw
  21. }
  22. }
  23.  
  24. int main()
  25. {
  26. // add functions to the map
  27. func_map["first"] = &f1;
  28. func_map["second"] = &f2;
  29. myMainFit("first", nullptr, 42);
  30. myMainFit("second", nullptr, 20);
  31. myMainFit("inexistent", nullptr, 10);
  32. }
  33.  
Success #stdin #stdout #stderr 0s 3276KB
stdin
Standard input is empty
stdout
f1
f2
stderr
Function "inexistent" is not in the map!