constexpr vs const vs constexpr const [英] constexpr vs const vs constexpr const
问题描述
const-vs-constexpr-on-variables
如果使用double ,那家伙对constexpr的说法是正确的($code>(或者当然是 float
)。但是,如果将var类型从 double
更改为int,char等整数类型,则一切正常。为什么会发生这种情况?
What the guy says about constexpr is right if double
is used (or float
of course). However, if you change the var type from double
to an integer type like int, char, etc, everything works. Why does that happen?
int main()
{
const int PI1 = 3;
constexpr int PI2 = 3;
constexpr int PI3 = PI1; // works
static_assert(PI1 == 3, ""); // works
const double PI1__ = 3.0;
constexpr double PI2__ = 3.0;
constexpr double PI3__ = PI1__; // error
static_assert(PI1__ == 3.0, ""); // error
return 0;
}
更新
:下一行是一个错误,我的意思是 PI3__ = PI1 __
Update
: the following line was a mistake, I meant PI3__ = PI1__
constexpr double PI3__ = PI1; // I meant PI1__
问题:
-
为什么
const int = 3
是编译时间常数,但const double = 3.0
不是吗?
Why
const int = 3
is compile time constant butconst double = 3.0
is not?
是否有任何原因我应该使用 constexpr const int val;
超过 constexpr int val
?两者似乎完全一样。
Is there any reason why I should use constexpr const int val;
over constexpr int val
? They both seem to do exactly the same.
推荐答案
从评论中似乎OP要求使用标准报价,该报价将 const int
定义为编译时常量,但将 const double
定义为编译时常量
From the comments it seems like OP is asking for Standard quote which defines const int
as a compile-time constant, but const double
as not.
相应的详细信息在5.19 常量表达式
中找到。特别是:
The corresponding details are found in 5.19, Constant Expressions
. In particular:
...左值到右值转换(4.1),除非应用于非整型或枚举类型的volatile glvalue,它引用具有初始化的
非易失性const对象,并使用常量表达式初始化
...
...an lvalue-to-rvalue conversion (4.1) unless it is applied to a non-volatile glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression...
int
是整数类型,而 double
不是。
int
is an integral type, while double
is not.
这篇关于constexpr vs const vs constexpr const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!