图片来源: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;
}
参考: