Allow for Range-Based For with enum classes?(允许基于范围的 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.)
这篇关于允许基于范围的 For 与枚举类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:允许基于范围的 For 与枚举类?
				
        
 
            
        基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 常量变量在标题中不起作用 2021-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				