Convert enum value to std::string in C++ (C++ enum 转 string)

Escape The Well / 2023-05-18 / 原文

 1 #include <iostream>
 2 #include <vector>
 3 
 4 #define DEFINE_ENUM(name, ...)\
 5 class name {\
 6 public:\
 7     name(size_t v): v_(v) {}\
 8     \
 9     enum { __VA_ARGS__ }; \
10     \
11     std::string ToString() {\
12         static std::vector<std::string> m = GetMappings();\
13         if (v_ > m.size()) {\
14             return #name ":-Invalid";\
15         }\
16         return m[v_];\
17     }\
18 private:\
19     std::vector<std::string> GetMappings() {\
20         const static std::string kEnumName = #name;\
21         std::vector<std::string> tokens;\
22         std::string s = #__VA_ARGS__; \
23         std::string token;\
24         for (char c : s) {\
25             if (c == ' ' || c == ',') {\
26                 if (!token.empty()) {\
27                     tokens.push_back(kEnumName + "::" + token);\
28                     token.clear();\
29                 }\
30             } else {\
31                 token += c;\
32             }\
33         }\
34         return tokens;\
35     }\
36     \
37 private:\
38     size_t v_;\
39 }
40 
41 DEFINE_ENUM(Weekday, 
42     Monday,
43     Tuesday, 
44 );
45 
46 int main() {
47     Weekday day = Weekday::Tuesday;
48     std::cout << day.ToString() << std::endl;
49     return 0;
50 }

打印结果:

Weekday::Tuesday