“枚举类”的递增和递减 [英] Incrementation and decrementation of “enum class”

查看:102
本文介绍了“枚举类”的递增和递减的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我们所知,C ++ 03中 enum 的递增和递减是非法的,因为C ++ 03 枚举可能不是连续的。但是,根据维基百科的说法,C ++ 11标准引入了新的枚举类,它更加类型安全,因为它不是基于任何简单的可数类型构建的。那么现在,如果我们有一个枚举值的有限列表,我们可以写一些类似

 枚举类颜色{黑色,蓝白色 }; 
// ...
颜色color = Colors :: White;
color ++;

,它将正常工作(例如增加 White 将返回黑色,减少黑色将返回白色)?



如果我们无法编写这样的代码,你是否知道任何类似行为的类,从 boost Qt 为我们提供了这个功能(正确的减少)?

解决方案


将正常工作


枚举不是按照您默认描述的方式环绕。



和C ++ 11的枚举类不保证连续的值,与C ++ 03的枚举相同。 p>

您可以为您的特定枚举定义包装行为。这个解决方案假设值是连续的,就像您描述的枚举一样。

 枚举类颜色{黑色,蓝色,白色,END_OF_LIST}; 

// ++颜色的特殊行为
颜色& operator $(Colors& c){
using IntType = typename std :: underlying_type< Colors> :: type
c = static_cast< Colors>(static_cast< IntType>(c)+ 1);
if(c == Colors :: END_OF_LIST)
c = static_cast< Colors>(0);
return c;
}

//颜色的特殊行为++
颜色操作符++(颜色& c,int){
颜色结果= c;
++ c;
返回结果;
}


As we know, incrementation and decrementation of enum in C++03 is illegal, because C++03 enum may not be continuous. But the C++11 standard introduced the new enum class construction, which, according to Wikipedia, is more type-safe because it isn’t built on any simple countable type. So now, if we have a bounded list of values of an enum, can we write something like

enum class Colors { Black, Blue, White };
// ...
Colors color = Colors::White;
color++;

and will it work correctly (e.g. incrementation of White will return Black and decrementation of Black will return White)?

If we can't write such code, do you know any behavior-like classes either from boost or from Qt that provide us this feature (correct in- and decrementing)?

解决方案

will it work correctly

No. enums are not designed to "wrap around" in the way you describe by default.

And C++11's enum class doesn't guarantee contiguous values, the same as you describe for C++03's enum.

You can define the wrapping behavior for your particular enum though. This solution assumes that the values are contiguous, like the enum you described.

enum class Colors { Black, Blue, White, END_OF_LIST };

// Special behavior for ++Colors
Colors& operator++( Colors &c ) {
  using IntType = typename std::underlying_type<Colors>::type
  c = static_cast<Colors>( static_cast<IntType>(c) + 1 );
  if ( c == Colors::END_OF_LIST )
    c = static_cast<Colors>(0);
  return c;
}

// Special behavior for Colors++
Colors operator++( Colors &c, int ) {
  Colors result = c;
  ++c;
  return result;
}

这篇关于“枚举类”的递增和递减的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆