C++ Enum转字符串


枚举类型定义如下

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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值