替换常量:什么时候使用静态constexpr和内联constexpr? [英] Replacing constants: when to use static constexpr and inline constexpr?
问题描述
此问题是对 C ++ 17的后续问题:仍使用枚举作为常量?。
旧式常量有几种形式,尤其是:
Legacy constants come in several forms, notably:
-
#define CONSTANT x
-
enum {CONSTANT = x};
-
const / * int / unsigned / whatever * / CONSTANT = x;
#define CONSTANT x
enum { CONSTANT = x };
const /*int/unsigned/whatever*/ CONSTANT = x;
关于静态constexpr
和 inline constexpr
常量的评论作为替换得到了我在考虑更新许多旧式常量(尤其是 #define
常量)的主题。
A comment about static constexpr
and inline constexpr
constants as a replacement got me thinking on the subject of updating our many, many legacy constants (particularly #define
constants).
可以理解,内联constexpr
值基本上只是被替换,就像内联函数一样(我被证明是错误的)。相反,静态constexpr
值作为二进制文件的一部分存储在单独的区域中。假设我理解正确,什么时候应该优先选择另一个?我的直觉是,对于整数常量,通常首选内联constexpr
。
As I understand, an inline constexpr
value is basically just substituted in place, like an inlined function (which I've been shown to be wrong about). Conversely, a static constexpr
value is stored as part of the binary in a separate area. Assuming I understand correctly, when should one be preferred over the other? My hunch is that, for integral constants, inline constexpr
will generally be preferred.
推荐答案
在C ++ 17中,替换名称空间范围标头中的那些旧习惯用法(例如 #define
)的正确方法是使用 constexpr内联
变量-和 not static
(这意味着:它们已经具有内部链接)了。
In C++17, the proper way to replace those old idioms (e.g. #define
) in headers in namespace scope is to use constexpr inline
variables -- and not static
(which is implied: they already have internal linkage).
虽然通常不会遇到ODR问题(因为您所描述的整数编译时常数很少使用ODR,并且在 inline
函数),现在最好将它们标记为 inline
,因为我们已经使用了该功能并避免了所有问题。
While typically you won't encounter ODR issues (because integer compile-time constants such as those you describe are rarely ODR-used and there is a provision for their typical usage within inline
functions), it is best to mark them as inline
now that we have the feature in the language and avoid all problems.
请参见标头中的const和constexpr变量应内联`以防止违反ODR?以获得有关它的技术详细信息。
See Should `const` and `constexpr` variables in headers be `inline` to prevent ODR violations? for the technical details about it.
这篇关于替换常量:什么时候使用静态constexpr和内联constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!