允许基于范围的 For 与枚举类?
我有一个循环代码块,其中我循环了 enum 类
的所有成员.
I have a recurrent chunk of code where I loop over all the members of an enum class
.
与新的 基于范围的 for
相比,我目前使用的 for
循环看起来非常笨拙.
The for
loop that I currently use looks very unwieldly compared to the new range-based for
.
有什么方法可以利用 C++11 的新特性来减少当前 for
循环的冗长?
Is there any way to take advantage of new C++11 features to cut down on the verbosity for my current for
loop?
我想改进的当前代码:
enum class COLOR
{
Blue,
Red,
Green,
Purple,
First=Blue,
Last=Purple
};
inline COLOR operator++( COLOR& x ) { return x = (COLOR)(((int)(x) + 1)); }
int main(int argc, char** argv)
{
// any way to improve the next line with range-based for?
for( COLOR c=COLOR::First; c!=COLOR::Last; ++c )
{
// do work
}
return 0;
}
换句话说,如果我能做这样的事情就好了:
In other words, it would be nice if I could do something like:
for( const auto& c : COLOR )
{
// do work
}
推荐答案
用枚举本身作为迭代器来迭代枚举是一个糟糕的主意,我建议使用实际的迭代器,如 deft_code 的答案.但如果这真的是你想要的:
Iterating enumerations with the enumeration itself as an iterator is a poor idea, and I recommend using an actual iterator as in deft_code's answer. But if this is really what you want:
COLOR operator++(COLOR& x) {
return x = (COLOR)(std::underlying_type<COLOR>::type(x) + 1);
}
COLOR operator*(COLOR c) {
return c;
}
COLOR begin(COLOR r) {
return COLOR::First;
}
COLOR end(COLOR r) {
COLOR l=COLOR::Last;
return ++l;
}
int main() {
//note the parenthesis after COLOR to make an instance
for(const auto& c : COLOR()) {
//do work
}
return 0;
}
在这里工作:http://ideone.com/cyTGD8
const COLOR COLORS[] = {COLOR::Blue, COLOR::Red, COLOR::Green, COLOR::Purple};
const COLOR (&COLORREF)[(int)COLOR::Last+1] = COLORS;
int main() {
for(const auto& c : COLORS) {
//do work
}
return 0;
}
如下所示:http://coliru.stacked-crooked.com/a/5d356cc91556d6ef
(如果颜色数量与数组中的元素数量不匹配,单独的定义和数组的引用会导致编译器错误.非常容易安全检查.)
(The separate defintinion and the reference of the array makes it a compiler error if the number of colors doesn't match the number of elements in the array. Excellent easy safety check.)
相关文章