有没有理由使用枚举来定义单个常量的C ++代码? [英] Is there a reason to use enum to define a single constant in C++ code?
问题描述
定义一个函数内部使用的整数常量的典型方法是:
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
和in-class 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?
推荐答案
原因主要是简洁。首先,枚举
可以是匿名的:
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
如果它是一个枚举
成员。如果你这样做:
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
被用于必需的整数常数表达式(即只允许它在哪里),它需要一个不定式的 foo :: bar。
需要这样的表达式的地方是:枚举
initializer, case
标签,数组大小(除了 new []
)和模板参数积分类型。因此,在其他地方使用 bar
技术上需要定义。有关更多信息,请参阅 C ++ Core Language Active Issue 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
变量而不需要定义。然而,角落的情况可能会有所不同,但是很多人认为只要使用匿名的枚举
,这一切都非常清晰,而且根本没有歧义。
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.
这篇关于有没有理由使用枚举来定义单个常量的C ++代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!