fork download
  1. #include <string>
  2. #include <iostream>
  3. #include <map>
  4. #include <stdexcept>
  5.  
  6. template<typename T>
  7. class Class1
  8. {
  9. typedef double(T::*memFunc)();
  10. std::map<std::string, memFunc> funcMap;
  11. public:
  12. void addFunc(std::string funcName, memFunc function)
  13. {
  14. funcMap.insert(std::pair<std::string, memFunc>(funcName, function));
  15. }
  16. double callFunc(const std::string& name, T& obj) const
  17. {
  18. typename std::map<std::string, memFunc>::const_iterator i = funcMap.find(name);
  19. if(i!=funcMap.end())
  20. return (obj.*(i->second))();
  21. else
  22. throw std::runtime_error("unknown function " + name);
  23. }
  24. };
  25.  
  26. class MyClass
  27. {
  28. public:
  29. MyClass()
  30. {
  31. class1.addFunc("new function", &MyClass::getValue);
  32. }
  33. double getValue()
  34. {
  35. return 3.14;
  36. }
  37. void callit()
  38. {
  39. std::cout << "called and got " << class1.callFunc("new function", *this) << '\n';
  40. }
  41. private:
  42. Class1<MyClass> class1;
  43. };
  44. int main()
  45. {
  46. MyClass mc;
  47. mc.callit();
  48. }
Success #stdin #stdout 0s 2860KB
stdin
Standard input is empty
stdout
called and got 3.14