fork(5) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class static_string
  5. {
  6. const char* const p_;
  7. const std::size_t sz_;
  8.  
  9. public:
  10. typedef const char* const_iterator;
  11.  
  12. template <std::size_t N>
  13. constexpr static_string(const char(&a)[N]) noexcept
  14. : p_(a)
  15. , sz_(N - 1)
  16. {}
  17.  
  18. constexpr static_string(const char* p, std::size_t N) noexcept
  19. : p_(p)
  20. , sz_(N)
  21. {}
  22.  
  23. constexpr const char* data() const noexcept { return p_; }
  24. constexpr std::size_t size() const noexcept { return sz_; }
  25.  
  26. constexpr const_iterator begin() const noexcept { return p_; }
  27. constexpr const_iterator end() const noexcept { return p_ + sz_; }
  28.  
  29. constexpr char operator[](std::size_t n) const
  30. {
  31. return n < sz_ ? p_[n] : throw std::out_of_range("static_string");
  32. }
  33. };
  34.  
  35. inline std::ostream& operator<<(std::ostream& os, static_string const& s)
  36. {
  37. return os.write(s.data(), s.size());
  38. }
  39.  
  40. /// \brief Get the name of a type
  41. template <class T>
  42. static_string typeName()
  43. {
  44. #ifdef __clang__
  45. static_string p = __PRETTY_FUNCTION__;
  46. return static_string(p.data() + 30, p.size() - 30 - 1);
  47. #elif defined(_MSC_VER)
  48. static_string p = __FUNCSIG__;
  49. return static_string(p.data() + 37, p.size() - 37 - 7);
  50. #endif
  51.  
  52. }
  53.  
  54. namespace details
  55. {
  56. template <class Enum>
  57. struct EnumWrapper
  58. {
  59. template < Enum enu >
  60. static static_string name()
  61. {
  62. #ifdef __clang__
  63. static_string p = __PRETTY_FUNCTION__;
  64. static_string enumType = typeName<Enum>();
  65. return static_string(p.data() + 73 + enumType.size(), p.size() - 73 - enumType.size() - 1);
  66. #elif defined(_MSC_VER)
  67. static_string p = __FUNCSIG__;
  68. static_string enumType = typeName<Enum>();
  69. return static_string(p.data() + 57 + enumType.size(), p.size() - 57 - enumType.size() - 7);
  70. #endif
  71. }
  72. };
  73. }
  74.  
  75. /// \brief Get the name of an enum value
  76. template <typename Enum, Enum enu>
  77. static_string enumName()
  78. {
  79. return details::EnumWrapper<Enum>::template name<enu>();
  80. }
  81.  
  82. enum class Color
  83. {
  84. Blue = 0,
  85. Yellow = 1
  86. };
  87.  
  88.  
  89. int main()
  90. {
  91. std::cout << "_" << typeName<Color>() << "_" << std::endl;
  92. std::cout << "_" << enumName<Color, Color::Blue>() << "_" << std::endl;
  93. return 0;
  94. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
_Color_
_Color::Blue_