C++ 中的 constexpr int 和 constexpr double

constexpr int and constexpr double in c++

提问人:bugatti1001 提问时间:10/23/2019 最后编辑:songyuanyaobugatti1001 更新时间:11/12/2020 访问量:2260

问:

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

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

有什么特别之处,所以它不能工作吗?doubleconstexpr

C++ C++11 整数 常量

评论

0赞 1201ProgramAlarm 10/23/2019
请参阅此问题

答:

5赞 songyuanyao 10/23/2019 #1

有什么特别之处,所以它不能工作吗?doubleconstexpr

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

对于核心常量表达式,在第 2 种情况下(带类型 )在常量表达式中可用,但在第 1 种情况下(带类型 )不可用。aintadouble

核心常量表达式是其计算结果将 不评估以下任何一项:

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

      • a. 应用于非易失性 glvalue,该值指定可在常量表达式中使用的对象(见下文),

        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
        }
        

(强调我的)

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

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

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

constexpr double a = 1.0;
constexpr double b = a;   // works fine now