我有一个循环代码块,我循环遍历 enum 类
的所有成员。
与新的基于范围的for
相比,我目前使用的for
循环看起来非常笨拙。
有什么方法可以利用新的 C++11 功能来减少当前 for
循环的冗长性?
我想改进的当前代码:
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;
}
换句话说,如果我能做这样的事情就好了:
for( const auto& c : COLOR )
{
// do work
}
最佳答案
我个人不喜欢为枚举重载 ++
运算符。通常递增一个枚举值并没有真正的意义。真正需要的只是一种迭代枚举的方法。
下面是一个支持迭代的通用Enum
类。它是功能性的,但不完整。真正的实现会很好地限制对构造函数的访问并添加所有迭代器特征。
#include <iostream>
template< typename T >
class Enum
{
public:
class Iterator
{
public:
Iterator( int value ) :
m_value( value )
{ }
T operator*( void ) const
{
return (T)m_value;
}
void operator++( void )
{
++m_value;
}
bool operator!=( Iterator rhs )
{
return m_value != rhs.m_value;
}
private:
int m_value;
};
};
template< typename T >
typename Enum<T>::Iterator begin( Enum<T> )
{
return typename Enum<T>::Iterator( (int)T::First );
}
template< typename T >
typename Enum<T>::Iterator end( Enum<T> )
{
return typename Enum<T>::Iterator( ((int)T::Last) + 1 );
}
enum class Color
{
Red,
Green,
Blue,
First = Red,
Last = Blue
};
int main()
{
for( auto e: Enum<Color>() )
{
std::cout << ((int)e) << std::endl;
}
}
关于c++ - 允许枚举类的基于范围的 For?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8498300/