枚举类型定义如下
enum Color {
Color_Red,
Color_Blue,
Color_Green,
kColor_Last = Color_Green,
};
const char* ToString(Color c);
c switch实现
const char* ToString(Color c)
{
switch (c) {
case Color_Red: return "Red";
case Color_Blue: return "Blue";
case Color_Green: return "Green";
default: return "";
}
}
c++ map实现
const char* ToString(Color c)
{
static std::map<Color, const char*> m = {
{Color_Red, "Red"}, {Color_Blue, "Blue"}, {Color_Green, "Green"}
};
return m[c];
}
c++ template实现
// 找到string所处的位置
bool find_string(size_t& index, const std::string& needle, const char* const haystack[], size_t max_index) {
for (index=0; index<max_index; ++index) {
if (strcasecmp(needle.c_str(), haystack[index]) == 0) {
return true;
}
}
return false;
}
template<class E>
struct Enum {
static const char** Names;
static size_t Size;
static inline const char* Name(E val) { return Names[val]; }
static inline bool Parse(E& val, const std::string& name) {
size_t index;
if (!find_string(index, name, Names, Size))
return false;
// 强制index为对应的枚举类型
val = static_cast<E>(index);
return true;
}
E val;
inline operator E&() { return val; }
inline Enum& operator=(E rhs) { val = rhs; return *this; }
inline const char* name() const { return Name(val); }
inline bool assign(const std::string& name) { return Parse(val, name); }
inline Enum& operator=(const std::string& rhs) { assign(rhs); return *this; }
};
// 定义Enum中的Names和Size
#define ENUM(e,n) \
template<> const char** Enum<e>::Names = n; \
template<> size_t Enum<e>::Size = sizeof(n)/sizeof(n[0])
static const char* kColor[kColor_Last+1] = {
"Red", "Blue", "Green"
};
ENUM(Color, kColor);
const char* ToString(Color c)
{
return Enum<Color>::Name(c);
}