在C ++中迭代通过连续枚举值的最简单的方法 [英] Simplest method for iterating through contiguous enum values in C++
问题描述
在C ++中使用连续值迭代枚举的首选简单方法是什么?我发现以前的SO这个问题涉及创建自定义操作符++
等,但这似乎过度。到目前为止,我想出的最好的是:
What is the preferred simple method for iterating through an enum with contiguous values in C++? I found previous SO questions on this subject which involved creating custom operator++
etc, but this seems like overkill. So far the best I have come up with is:
enum {
FOO,
BAR,
BLECH,
NUM_ENUMS
} MyEnum;
//for (MyEnum m = FOO; m < NUM_ENUMS; ++m) // compile error
// ...
//for (MyEnum m = FOO; m < NUM_ENUMS; m = m + 1) // compile error
// ...
for (MyEnum m = FOO; m < NUM_ENUMS; m = MyEnum(m + 1)) // OK ?
...
从编码风格的角度来看,这是合理的,警告( g ++ -Wall ...
似乎对此感到满意)?
Is this reasonable from a coding style perspective and is it likely to generate warnings (g++ -Wall ...
seems happy with this) ?
推荐答案
<
这将是未定义的: MyEnum(int(NUM_ENUMS)+ 1)
因为保持(4)的值将大于枚举可以表示的值([0,3]);由于您确保 m
严格低于 NUM_ENUMS
,可以安全地使用 MyEnum + 1)
。
This would have been undefined: MyEnum(int(NUM_ENUMS) + 1)
because the value to hold (4) would be greater than what the enum can represent ([0, 3]); since you ensure that m
is strictly lower than NUM_ENUMS
it is safe to use MyEnum(m + 1)
.
另一方面,请注意,您会遇到自定义枚举的问题,例如:
On the other hand, note that you would have issues with customized enums such as:
enum OtherEnum {
Foo = -1,
Bar = 2,
Baz = 8,
NUM_OTHERENUM
};
因此不是通用做法。
我建议生成的数组迭代,代替:
I would advise a generated array to iterate over instead:
MyEnum const Values[] = { FOO, BAR, BLECH };
请注意,它很容易从枚举的定义生成,无意义的价值(商业智慧)。
Note that it is easily generated from the definition of the enum, and also avoid polluting the interface with a nonsensical value (business-wise).
这篇关于在C ++中迭代通过连续枚举值的最简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!