是否有理由使用枚举在 C++ 代码中定义单个常量?
定义在函数内部使用的整数常量的典型方法是:
The typical way to define an integer constant to use inside a function is:
const int NumbeOfElements = 10;
在类中使用相同:
class Class {
...
static const int NumberOfElements = 10;
};
然后它可以用作固定大小的数组绑定,这意味着它在编译时是已知的.
It can then be used as a fixed-size array bound which means it is known at compile time.
很久以前编译器不支持后一种语法,这就是使用枚举的原因:
Long ago compilers didn't support the latter syntax and that's why enums were used:
enum NumberOfElementsEnum { NumberOfElements = 10; }
现在几乎所有广泛使用的编译器都支持函数内 const int
和类内 static const int
语法,是否有任何理由将枚举用于这个目的?
Now with almost every widely used compiler supporting both the in-function const int
and the in-class static const int
syntax is there any reason to use the enum for this purpose?
推荐答案
原因主要是简洁.首先,enum
可以是匿名的:
The reason is mainly brevity. First of all, an enum
can be anonymous:
class foo {
enum { bar = 1 };
};
这有效地将 bar
引入为一个整数常量.注意上面的比static const int
要短.
This effectively introduces bar
as an integral constant. Note that the above is shorter than static const int
.
此外,如果 &bar
是 enum
成员,则没有人可能会编写它.如果你这样做:
Also, no-one could possibly write &bar
if it's an enum
member. If you do this:
class foo {
static const int bar = 1;
}
然后您班级的客户这样做:
and then the client of your class does this:
printf("%p", &foo::bar);
然后他会得到一个编译时链接器错误,指出 foo::bar
没有定义(因为,??作为一个左值,它没有定义).在实践中,就目前的标准而言,任何使用 bar
的地方需要 整型常量表达式(即只允许它的地方),它需要一个 outfoo::bar.
的类定义.需要这样表达式的地方是:enum
初始值设定项、case
标签、数组大小类型(new[]
除外)和整型的模板参数.因此,在技术上在其他任何地方使用 bar
都需要定义.有关更多信息,请参阅 C++ 核心语言活动问题 712信息 - 目前还没有提议的解决方案.
then he will get a compile-time linker error that foo::bar
is not defined (because, well, as an lvalue, it's not). In practice, with the Standard as it currently stands, anywhere bar
is used where an integral constant expression is not required (i.e. where it is merely allowed), it requires an out-of-class definition of foo::bar.
The places where such an expression is required are: enum
initializers, case
labels, array size in types (excepting new[]
), and template arguments of integral types. Thus, using bar
anywhere else technically requires a definition. See C++ Core Language Active Issue 712 for more info - there are no proposed resolutions as of yet.
在实践中,如今大多数编译器对此更加宽容,并且可以让您摆脱对 static const int
变量的大多数常识"用法,而无需定义.然而,极端情况可能会有所不同,然而,很多人认为只使用匿名 enum
更好,因为它的一切都非常清晰,完全没有歧义.
In practice, most compilers these days are more lenient about this, and will let you get away with most "common sense" uses of static const int
variables without requiring a definition. However, the corner cases may differ, however, so many consider it to be better to just use anonymous enum
, for which everything is crystal clear, and there's no ambiguity at all.
相关文章