gpt4 book ai didi

c++ - constexpr vs const vs constexpr const

转载 作者:太空狗 更新时间:2023-10-29 20:55:13 27 4
gpt4 key购买 nike

const-vs-constexpr-on-variables

这家伙说的constexpr是对的if double使用(当然是float)。但是,如果您将 var 类型从 double 更改为对于整数类型,如 int、char 等,一切正常。为什么会这样?

http://ideone.com/DAWABE

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;
}

Update : 下面这行是个错误,我的意思是 PI3__ = PI1__

constexpr double PI3__ = PI1;  // I meant PI1__

问题:

  1. 为什么 const int = 3是编译时间常数但是 const double = 3.0不是?

  2. 我应该使用 constexpr const int val; 有什么理由吗?在 constexpr int val ?他们似乎做的完全一样。

最佳答案

根据您在评论中的回答,这是我的回答。 C++ 标准非常清楚。 GCC 5.1 在这里工作得很好:https://godbolt.org/g/2oV6Hk

A converted constant expression of type T is an expression, implicitly converted to type T, where the converted expression is a constant expression and the implicit conversion sequence contains only § 5.20 134 c ISO/IEC N4567

[...]

(4.6) — integral promotions (4.5),

(4.7) — integral conversions (4.7) other than narrowing conversions (8.5.4),

[...]

n4567中narrowing conversions (8.5.4/7)的引用:

A narrowing conversion is an implicit conversion

  • from a floating-point type to an integer type, or
  • from long double to double or float, or from double to float, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly), or
  • from an integer type or unscoped enumeration type to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type, or
  • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type.

关于c++ - constexpr vs const vs constexpr const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36405541/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com