fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. #include <array>
  5. #include <stdexcept>
  6.  
  7. // you did not show what 'my_type' actually looks like. As this site does
  8. // not support C++17, so I'm just using a placeholder for demo purposes.
  9. // In C++17 and later, std::variant would make more sense...
  10. struct my_type {
  11. enum {v_int, v_double, v_string} type;
  12. //...
  13. explicit my_type(int i) : type(v_int) { }
  14. explicit my_type(double d) : type(v_double) { }
  15. explicit my_type(std::string s) : type(v_string) { }
  16. };
  17.  
  18. // As this site does not support C++17, I'm using template specialization
  19. // to handle multiple template parameter types. In C++17 and later,
  20. // 'if constexpr (std::is_same_v<T, ...>)' can be used instead...
  21. template<class T>
  22. std::string my_fun(my_type complex_object)
  23. {
  24. /*
  25. if constexpr (std::is_same_v<T, int>)
  26. return "my_func<int>";
  27. if constexpr (std::is_same_v<T, double>)
  28. return "my_func<double>";
  29. if constexpr (std::is_same_v<T, std::string>)
  30. return "my_func<string>";
  31. */
  32. return "my_func<T>";
  33. }
  34.  
  35. template<>
  36. std::string my_fun<int>(my_type complex_object)
  37. {
  38. return "my_func<int>";
  39. }
  40.  
  41. template<>
  42. std::string my_fun<double>(my_type complex_object)
  43. {
  44. return "my_func<double>";
  45. }
  46.  
  47. template<>
  48. std::string my_fun<std::string>(my_type complex_object)
  49. {
  50. return "my_func<string>";
  51. }
  52.  
  53. // now, for the mapping code...
  54.  
  55. constexpr std::array<const char*,3> my_ids = {"int", "double", "string"};
  56.  
  57. using my_func_type = std::string(*)(my_type);
  58.  
  59. const std::map<std::string, my_func_type> my_funcs = {
  60. {"int", &my_fun<int>},
  61. {"double", &my_fun<double>},
  62. {"string", &my_fun<std::string>}
  63. };
  64.  
  65. const char* get_info(my_type complex_object)
  66. {
  67. return my_ids[complex_object.type];
  68. }
  69.  
  70. std::string my_disp_fun(my_type complex_object)
  71. {
  72. const char* id = get_info(complex_object);
  73. auto iter = my_funcs.find(id);
  74. if (iter == my_funcs.end())
  75. throw std::runtime_error("unknown object type");
  76. return iter->second(complex_object);
  77. }
  78.  
  79. int main()
  80. {
  81. std::cout << my_disp_fun(my_type{12345}) << std::endl;
  82. std::cout << my_disp_fun(my_type{123.45}) << std::endl;
  83. std::cout << my_disp_fun(my_type{std::string("hi")}) << std::endl;
  84. return 0;
  85. }
Success #stdin #stdout 0s 5040KB
stdin
Standard input is empty
stdout
my_func<int>
my_func<double>
my_func<string>