C++ 中的 constexpr int 和 constexpr double

bug*_*001 7 c++ double integer constexpr c++11

我遇到了一个奇怪的案例。

// this does not work, and reports:
// constexpr variable 'b' must be initialized by a constant expression
int main() {
  const double a = 1.0;
  constexpr double b = a;
  std::cout << b << std::endl;
}

// this works...
int main() {
  const int a = 1;
  constexpr int b = a;
  std::cout << b << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

有什么特别之处double所以它不能constexpr工作?

son*_*yao 6

有什么特别的地方double所以它不能constexpr工作吗?

int在这种情况下s 和doubles 的行为不同。

对于核心常量表达式a在第二种情况(带有 type int)可用于常量表达式,但a在第一种情况(带有 type double)则不能。

核心常量表达式是其计算不会计算以下任何一项的任何表达式:

    1. 左值到右值的隐式转换,除非......

      • A。应用于指定可在常量表达式中使用的对象的非易失性泛左值(见下文),

        int main() {
            const std::size_t tabsize = 50;
            int tab[tabsize]; // OK: tabsize is a constant expression
                              // because tabsize is usable in constant expressions
                              // because it has const-qualified integral type, and
                              // its initializer is a constant initializer
        
            std::size_t n = 50;
            const std::size_t sz = n;
            int tab2[sz]; // error: sz is not a constant expression
                          // because sz is not usable in constant expressions
                          // because its initializer was not a constant initializer
        }
        
        Run Code Online (Sandbox Code Playgroud)

(强调我的)

可在常量表达式中使用 在上面的列表中,变量可以在常量表达式中使用,如果它是

  • constexpr 变量,或者
  • 它是一个常量初始化变量
    • 参考类型或
    • const 限定的整型或枚举类型。

您可以声明aasconstexpr使其可在常量表达式中使用。例如

constexpr double a = 1.0;
constexpr double b = a;   // works fine now
Run Code Online (Sandbox Code Playgroud)