【发布时间】:2012-01-19 20:42:18
【问题描述】:
我有一段重复的代码,我循环遍历 enum class 的所有成员。
与新的range-based 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
}
【问题讨论】:
-
有趣。自 1983 年以来,Ada 就有此功能。
-
(COLOR)(((int)(x) + 1))而不是int,请考虑使用std::underlying_type<COLOR>::type。 -
预计会跳过 Purple 吗?
-
@kfmfe04
std::underlying_type是 not supported on GCC 4.6。它将在 4.7 上得到支持。这里有一个近似的模拟:stackoverflow.com/a/7932617/46642. -
啊!这么快就接受了。我通常会等待 24 小时,以便让所有时区都有机会提出更好的答案。