【发布时间】:2010-10-03 17:20:07
【问题描述】:
通常,需要同时使用多个枚举类型。有时,一个人有一个名字冲突。想到了两个解决方案:使用命名空间,或使用“更大”的枚举元素名称。不过,命名空间解决方案有两种可能的实现方式:具有嵌套枚举的虚拟类,或完整的命名空间。
我正在寻找所有三种方法的优缺点。
例子:
// oft seen hand-crafted name clash solution
enum eColors { cRed, cColorBlue, cGreen, cYellow, cColorsEnd };
enum eFeelings { cAngry, cFeelingBlue, cHappy, cFeelingsEnd };
void setPenColor( const eColors c ) {
switch (c) {
default: assert(false);
break; case cRed: //...
break; case cColorBlue: //...
//...
}
}
// (ab)using a class as a namespace
class Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; };
class Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; };
void setPenColor( const Colors::e c ) {
switch (c) {
default: assert(false);
break; case Colors::cRed: //...
break; case Colors::cBlue: //...
//...
}
}
// a real namespace?
namespace Colors { enum e { cRed, cBlue, cGreen, cYellow, cEnd }; };
namespace Feelings { enum e { cAngry, cBlue, cHappy, cEnd }; };
void setPenColor( const Colors::e c ) {
switch (c) {
default: assert(false);
break; case Colors::cRed: //...
break; case Colors::cBlue: //...
//...
}
}
【问题讨论】:
-
首先,我会使用 Color::Red、Feeling:Angry 等
-
好问题,我使用了命名空间方法.... ;)
-
所有东西上的“c”前缀都会影响可读性。
-
请注意,你不需要像
enum e {...}那样命名枚举,枚举可以是匿名的,即enum {...},这在包装在命名空间或类中时更有意义。 -
如果你有一个未命名的枚举,它的类型是什么?例如:枚举 FOO{};空栏(FOO e);但如果我们有 enum{} void bar2(???);