constexpr 是 C++11 引入的,可用来让表达式核定于编译器。
constexpr int square(int x)
{
return x * x
}
float a[square(9)]; // OK since C++11: a has 81 elements
另外这个关键字修正了一个在C++98使用数值极限时出现的问题。
/*在C++11之前,如下式子无法被用作一个整数常量,虽然它功能上等同于INT_MAX:*/
std::numeric_limits<short>::max()
/*在如今C++11中,这样一个式子被声明为constexpr,于是举个例子,可以用它来声明array或进行
编译器运算(所谓metaprogramming):*/
std::array<float, std::numeric_limits<short>::max()> a;