fork(1) download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. namespace internal
  5. {
  6.  
  7. #ifdef _MSC_VER
  8. #define FUNC_MACRO __FUNCTION__
  9. static const char FRONT[] = "GetTypeNameHelper<";
  10. static const char BACK[] = ">::GetTypeName";
  11. #else
  12. #define FUNC_MACRO __PRETTY_FUNCTION__
  13. static const char FRONT[] = "T = ";
  14. static const char BACK[] = ";";
  15. static const char BACK_ALT[] = "]";
  16. #endif
  17.  
  18. template <typename T>
  19. struct GetTypeNameHelper
  20. {
  21. static const std::string GetTypeName(void)
  22. {
  23.  
  24. std::string func_str = FUNC_MACRO;
  25. size_t front_pos = func_str.find(FRONT) + sizeof(FRONT) - 1;
  26. size_t back_pos = func_str.find(BACK);
  27.  
  28. #ifndef _MSC_VER
  29. if (back_pos == std::string::npos)
  30. back_pos = func_str.find(BACK_ALT);
  31. #endif
  32.  
  33. if (front_pos == std::string::npos || back_pos == std::string::npos)
  34. return "GetTypeNameError";
  35.  
  36. return func_str.substr(front_pos, back_pos - front_pos);
  37. }
  38. };
  39. }
  40.  
  41. template <typename T>
  42. const std::string GetTypeName(void)
  43. {
  44. return internal::GetTypeNameHelper<T>::GetTypeName();
  45. }
  46.  
  47. struct foo {};
  48. struct bar {};
  49.  
  50. template <class T1, class T2>
  51. struct templated_struct {};
  52.  
  53. int main() {
  54. std::cout << GetTypeName<foo>() << '\n';
  55. std::cout << GetTypeName<bar>() << '\n';
  56. std::cout << GetTypeName< templated_struct<foo, int> >() << '\n';
  57.  
  58. std::cout << GetTypeName<int>() << '\n';
  59. std::cout << GetTypeName<float>() << '\n';
  60. }
  61.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
foo
bar
templated_struct<foo, int>
int
float