“枚举类”的递增和递减 [英] Incrementation and decrementation of “enum class”
问题描述
我们知道,C ++ 03中 enum
的递增和递减是非法的,因为C ++ 03 enum
可以不连续。但是C ++ 11标准引入了新的枚举类
构造,根据维基百科,它更加类型安全,因为它不是建立在任何简单的可数类型上。现在,如果我们有一个枚举值的有限列表,我们可以写像
枚举类Colors {Black,蓝,白};
// ...
颜色color = Colors :: White;
color ++;
并可正常工作(例如增加 White
将返回 Black
,并且减少 Black
将返回 White
)
如果我们不能编写这样的代码,你知道任何类似行为的类吗? boost
或 Qt
为我们提供此功能(正确递减和递减)?
否。 enum
不是为了以默认方式描述的方式环绕。
和C ++ 11的类枚举
不保证连续的值,与您对C ++ 03的枚举
描述的相同。 p>
你可以为你的特定枚举定义包装行为。
枚举类Colors {黑色,蓝色,白色,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;
return result;
}
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. enum
s are not designed to "wrap around" in the way you describe by default.
And C++11's class enum
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屋!