c++ - C++ 中的 constexpr int 和 constexpr double

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

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

// 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 工作吗?

最佳答案

anything special about double so it cannot make constexpr work?

intdouble 在这种情况下表现不同。

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

A core constant expression is any expression whose evaluation would not evaluate any one of the following:

    1. an lvalue-to-rvalue implicit conversion unless....

      • a. applied to a non-volatile glvalue that designates an object that is usable in constant expressions (see below),

        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
        }
        

(强调我的)

Usable in constant expressions In the list above, a variable is usable in constant expressions if it is

  • a constexpr variable, or
  • it is a constant-initialized variable
    • of reference type or
    • of const-qualified integral or enumeration type.

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

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

关于c++ - C++ 中的 constexpr int 和 constexpr double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58514970/

相关文章:

c++ - 这个 boost::tuple 代码可以转换为纯 std::standard 库代码吗?

pointers - 当只有一个所有者(std::unique_ptr)但其他对象需要该对象的 "handle"时,C++11 是否应该使用原始指针?

c++ - const 类名 &obj == 类名 const &obj?

javascript - 如何在原始 Javascript 中将对象转换为具有正确数据类型的数组?

c++ - WM_MOUSEWHEEL 停止工作,而其他事件仍在 WinAPI (C++) 中工作

c++ - 十六进制到十进制与 char 给出奇怪的结果?

python - 定义 3-D 空间中变换估计的精度

c++ - c++11 中的关键字 typeof

java - JMeter Beanshell 整数错误

c++ - 在 cpp 中将 int16 转换为 double