为什么不能增加枚举类型的变量? [英] Why can't I increment a variable of an enumerated type?
问题描述
我有一个枚举类型 StackID
,我使用枚举来引用特定向量的索引,它使我的代码更容易阅读。
但是,现在我需要创建一个 nextAvail 变量
StackID
。 (它实际上是指一个特定的stackID)。我试图增加它,但在C ++,以下是非法的:
nextAvail ++;
对我来说有什么意义...因为没有边界检查。
$我可能会忽略某些明显的东西,我还想链接到此问题。
我可能忽略了一些明显的东西,但什么是好的替代品?
重载运算符++
:
//小心,大脑编译代码!
StackID& operator ++(StackID& stackID)
{
#if MY_ENUMS_ARE_CONTIGUOUS&& I_DO_NOT_WORRY_ABOUT_OVERFLOW
return stackID = static_cast< StackID>(++ static_cast< int>(stackID));
#else
switch(stackID){
case value1:return stackID = value2;
case value2:return stackID = value3;
...
case valueN:return stackID = value1;
}
assert(false);
return stackID; //一些编译器可能会警告否则
#endif
}
StackID运算符++(StackID& stackID,int)
{
StackID tmp(stackID);
++ stackID;
return tmp;
}
I have a enumerated type StackID
, and I am using the enumeration to refer to an index of a particular vector and it makes my code easier to read.
However, I now have the need to create a variable called nextAvail
of type StackID
. (it actually refers to a particular stackID ). I tried to increment it but in C++, the following is illegal:
nextAvail++;
Which sort of makes sense to me ... because there's no bounds checking.
I'm probably overlooking something obvious, but what's a good substitute?
I also want to link to this question.
I'm probably overlooking something obvious, but what's a good substitute?
Overloading operator++
:
// Beware, brain-compiled code ahead!
StackID& operator++(StackID& stackID)
{
#if MY_ENUMS_ARE_CONTIGUOUS && I_DO_NOT_WORRY_ABOUT_OVERFLOW
return stackID = static_cast<StackID>( ++static_cast<int>(stackID) );
#else
switch(stackID) {
case value1 : return stackID = value2;
case value2 : return stackID = value3;
...
case valueN : return stackID = value1;
}
assert(false);
return stackID; // some compilers might warn otherwise
#endif
}
StackID operator++(StackID& stackID, int)
{
StackID tmp(stackID);
++stackID;
return tmp;
}
这篇关于为什么不能增加枚举类型的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!