现在的位置: 首页 > 综合 > 正文

封装C++ enum ,并设置enum 的名字

2013年08月07日 ⁄ 综合 ⁄ 共 1179字 ⁄ 字号 评论关闭

 

/*!
 * \b author: Peng Futian 
 *
 * \b Date: 2011-07-30
 *
 * \b Description: 将enum封装在struct中,并且设置enum的名字
 * 用法:
 *  类型定义,为了与数组中的名字对应,元素值应该用系统缺省的设置,从0开始
 *  DECLARE_MV_ENUM(FileShare, 10)
 *   Read,
 *   Write,
 *  END_DECLARE_MV_ENUM()
 *
 *  实现部分,需要与定义中相应元素位置一一对应
 *  IMPLEMENT_MV_ENUM(E)
 *   "Read",
 *   "Write"
 *  END_IMPLEMENT_MV_ENUM()
 *
 *  @param E 类型名
 *  @param S 元素的个数
 *
 */
#define DECLARE_MV_ENUM(E, S) \
struct E \
{ \
private: \
 static std::string name_list_[];\
public: \
  E(const int type = 0) : type_((Type)type) { \
  } \
  E(const E& rhs) : type_(rhs.type_) { \
  } \
  E& operator=(const E& rhs) { \
    if(this != &rhs) {\
      this->type_ = rhs.type_; \
    } \
    return *this; \
  } \
  E& operator=(const int type) { \
    this->type_ = (Type)type; \
    return *this; \
  } \
  bool operator==(const E& rhs) const { \
    return type_ == rhs.type_; \
  } \
  operator int() const { \
    return this->type_; \
  } \
  const std::string& GetName() const{\
   return name_list_[type_]; \
  } \
  static const int SIZE = S;\
  enum Type \
  {

#define END_DECLARE_MV_ENUM() \
  }; \
  static const std::string& GetName(const Type type) { \
    return name_list_[type]; \
  } \
  bool operator==(const Type& type) const { \
    return type_ == type; \
  } \
  private: \
    Type type_; \
};

#define IMPLEMENT_MV_ENUM(E) \
  std::string E::name_list_[] = \
  {

#define END_IMPLEMENT_MV_ENUM() \
  };

抱歉!评论已关闭.