【问题标题】:constexpr int and constexpr double in c++C++ 中的 constexpr int 和 constexpr double
【发布时间】:2020-02-19 05:39:15
【问题描述】:

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

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

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

【问题讨论】:

标签: c++ c++11 integer double constexpr


【解决方案1】:

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

ints 和 doubles 在这种情况下表现不同。

对于core constant expressiona 在第二种情况下(类型为int)是usable in constant expressions,但a 在第一种情况下(类型为double)不是。

核心常量表达式是其求值将 不评估以下任何一项:

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

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

        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 变量,或
  • 它是一个常量初始化变量
    • 引用类型或
    • const 限定整数或枚举类型。

您可以将a 声明为constexpr 以使其可用于常量表达式。例如

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2015-11-01
    • 2017-07-29
    • 1970-01-01
    • 2018-03-11
    相关资源
    最近更新 更多