int sz;
constexpr auto arraySize1 = sz; // error! sz's value unknown at compilation
std::array<int, sz> data1; // error! same problem
constexpr auto arraySize2 = 10; // fine, 10 is a compile-time constant
std::array<int, arraySize2> data2; // fine, arraySize2 is constexpr
int sz;
const auto arraySize = sz; // fine, arraySize is const copy of sz
std::array<int, arraySize> data; // error! arraySize's value unknown at compilation
constexpr int max = 100;
void use(int n)
{
constexpr int c1 = max+7; // OK: c1 is 107
constexpr int c2 = n+7; // Error: we don’t know the value of c2
// ...
}
要处理这样的情况,即一个“变量”的值在编译时是未知的,但在初始化后从未改变,
c++提供了第二种形式的常量(常量)。
例如:< / p >
constexpr int max = 100;
void use(int n)
{
constexpr int c1 = max+7; // OK: c1 is 107
const int c2 = n+7; // OK, but don’t try to change the value of c2
// ...
c2 = 7; // error: c2 is a const
}
int main()
{
int n;
cin >> n;
const int c = n; // OK: 'c' can also be initialized at run time
constexpr int e = n; // Error: 'e' must be initialized at compile time
}
注意: constexpr通常在编译时求值,但不保证这样做,除非它们被调用
.在需要常量表达式的上下文中
constexpr int add(int a, int b)
{
return a + b;
};
int main()
{
int n = add(4, 3); // may or may not be computed at compile time
constexpr int m = add(4,3); // must be computed at compile time
}