我遇到了一个奇怪的案例。
// 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 makeconstexpr
work?
int
和 double
在这种情况下表现不同。
对于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:
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/