为什么 Phobos 使用枚举作为常量?
为什么Phobos使用enum
来定义常量?例如,在 std.math 中:
enum real E = 2.7182818284590452354L;
为什么不使用全局不可变
?与 immutable
相比,enum
的优点/缺点是什么?
Why does Phobos use enum
to define constants? For example, in std.math:
enum real E = 2.7182818284590452354L;
Why not use a global immutable
? What are the advantages/disadvantages of enum
over immutable
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,对于编译时常量而不是运行时常量,使用枚举没有任何缺点,而且它的优点是使您的意图绝对清晰并且效率更高。
编辑:枚举的另一种用例可以向编译器明确函数是否应该在运行时或编译时求值。如果函数的结果被分配给
不可变
堆栈变量,则该函数将在运行时计算。如果您在同一范围内使用enum
,则将在编译时评估结果。In general, for things that are compile-time constants as opposed to runtime constants, there's no disadvantage to using an enum, and it has the advantages of making your intentions absolutely clear and being marginally more efficient.
Edit: One other use case for enums can be disambiguating to the compiler whether a function should be evaluated at runtime or compile time. If the result of a function is assigned to an
immutable
stack variable, the function will be evaluated at runtime. If you use anenum
in the same scope, the result will be evaluated at compile time.D
enum A = B;
中的 IIRC 与 C 中的#define A B
或多或少相同。在任何使用它。IIRC in D
enum A = B;
is more or less the same things as#define A B
is in C. It is always subbed in as a literal in any expression that uses it.