问题描述
C ++ 17更新:
静态constexpr
变量隐式地 inline
因此不需要外部定义。
原始问题:
假设我有一个常量列表,例如
struct Cls {
静态constexpr int N = 32 ;
静态constexpr int M = 64;
};
这当然表明我为它们添加了定义,以避免可能发生的ODR使用问题,所以我需要:
constexpr int Cls :: N;
constexpr int Cls :: M;
为什么应该我更喜欢
struct Cls {
枚举:int {
N = 32,
M = 64
};
};
从 N 和
M
更真正地只是常量,而不是本身具有对象的对象(如果这仅是标头,则更大),并且更短。我可以明确指定类型 enum:long long
或任何需要的类型。第一个优点是什么?
解决方案
一个区别是,您可以使用
的地址。静态constexpr
而不是 enum
。
另一个是 constexpr
不支持该语言的较早版本(它是C ++ 11中引入的)。
我会使用枚举
仅在两个值属于同一值时。我还要给枚举
一个描述这种关系的名称。我不会使用枚举
来定义不相关的常量。
C++17 Update:static constexpr
variables are implicitly inline
so there's no external definition necessary.
Original question:
Let's say I have a list of constants such as
struct Cls {
static constexpr int N = 32;
static constexpr int M = 64;
};
This of course suggests that I add definitions for these to avoid ODR-usage issues that may occur so I need:
constexpr int Cls::N;
constexpr int Cls::M;
Why should I prefer this over
struct Cls {
enum : int {
N = 32,
M = 64
};
};
Which saves me of the ODR-usage headaches since N
and M
are more truly just constants and not objects in their own right (a bigger deal if this is header-only) and is shorter. I could explicitly specify the type enum : long long
or whatever if need be. What is the advantage of the first?
解决方案 One difference is that you can take the address of a static constexpr
but not of an enum
.
Another is that constexpr
isn't supported by older versions of the language (it was introduced in C++11).
I'd use enum
only if the values belong together. I'd also give the enum
a name that describes that relationship. I wouldn't use an enum
for defining unrelated constants.
这篇关于为什么对于类级别的积分常量,我为什么更喜欢在类中使用静态constexpr int而不是枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!