允许基于范围对于枚举类? [英] Allow for Range-Based For with enum classes?
问题描述
我有一个循环的代码块,其中我循环枚举类
的所有成员。
我现在使用的循环与
基于范围的新
相比看起来很不实用。
有没有办法利用新的C ++ 11功能来减少我当前 for
循环的详细程度? / p>
我想改进的当前代码:
枚举类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)
{
//以任何方式改进基于范围的下一行?
for(COLOR c = COLOR :: First; c!= COLOR :: Last; ++ c)
{
// do work
}
return 0 ;
}
换句话说, / p>
for(const auto& c:COLOR)
{
// do work
}
枚举本身作为迭代器迭代枚举是糟糕的主意,我建议使用一个实际的迭代器,如deft_code的答案。但是如果这真的是你想要的:
COLOR运算符++(COLOR& x){return x =(COLOR) :underlying_type< COLOR> :: type(x)+ 1); }
COLOR操作符*(COLOR c){return c;}
COLOR begin(COLOR r){return COLOR :: First;}
COLOR end(COLOR r){COLOR l = COLOR ::持续;返回l ++;}
int main(){
for(const auto& c:COLOR()){//注意我在这里添加了括号来创建一个实例
// do work
}
return 0;
}
在这里工作: http://ideone.com/cyTGD8
I have a recurrent chunk of code where I loop over all the members of an enum class
.
The for
loop that I currently use looks very unwieldly compared to the new range-based for
.
Is there any way to take advantage of new C++11 features to cut down on the verbosity for my current for
loop?
Current Code that I would like to improve:
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
}
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() {
for(const auto& c : COLOR()) { //note I added parenthesis here to make an instance
//do work
}
return 0;
}
Working here: http://ideone.com/cyTGD8
这篇关于允许基于范围对于枚举类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!