图片来源:https://www.pixiv.net/artworks/97951009
直接映射枚举值名称
#ifndef COLOR_H
#define COLOR_H
#define DEF_COLORS \
X(RED) \
X(ORANGE) \
X(YELLOW) \
X(GREEN) \
X(CYAN) \
X(BLUE) \
X(PURPLE)
enum Color {
#define X(name) name,
DEF_COLORS
#undef X
color_count
};
const char* ColorToStr(Color c) {
switch (c) {
#define X(name) case name : return #name;
DEF_COLORS
#undef X
default:
return "";
}
}
#endif /* COLOR_H */
映射指定字符串
#ifndef COLOR_H
#define COLOR_H
#define DEF_COLORS \
X(RED, "红") \
X(ORANGE, "橙") \
X(YELLOW, "黄") \
X(GREEN, "绿") \
X(CYAN, "青") \
X(BLUE, "蓝") \
X(PURPLE, "紫")
enum Color {
#define X(name, str) name,
DEF_COLORS
#undef X
color_count
};
const char* ColorToStr(Color c) {
switch (c) {
#define X(name, str) case name : return str;
DEF_COLORS
#undef X
default:
return "";
}
}
#endif /* COLOR_H */
测试代码
#include <iostream>
#include "color.h"
int main() {
for (size_t i = 0; i < size_t(Color::color_count); i++) {
std::cout << ColorToStr(Color(i)) << std::endl;
}
return 0;
}
参考:
- https://stackoverflow.com/questions/201593/is-there-a-simple-way-to-convert-c-enum-to-string
- https://belaycpp.com/2021/08/24/best-ways-to-convert-an-enum-to-a-string/
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。