为确保constexpr
函数在编译时被评估,您必须通过制作结果来强制它们constexpr
。例如:
#include <array>
int
main()
{
constexpr std::array<int, 5> arr{1, 2, 3, 4, 5};
int i = arr[6]; // run time error
}
然而:
#include <array>
int
main()
{
constexpr std::array<int, 5> arr{1, 2, 3, 4, 5};
constexpr int i = arr[6]; // compile time error
}
不幸的是,要使其真正起作用,std::array
必须符合 C++14 规范,而不是 C++11 规范。由于 C++11 规范没有标记with的const
重载。std::array::operator[]
constexpr
所以在 C++11 中你不走运。在 C++14 中,您可以使其工作,但array
前提是调用索引运算符的 the 和结果均已声明constexpr
。
澄清
数组索引的 C++11 规范如下:
reference operator[](size_type n);
const_reference operator[](size_type n) const;
数组索引的 C++14 规范如下:
reference operator[](size_type n);
constexpr const_reference operator[](size_type n) const;
Ieconstexpr
被添加到const
C++14 的重载中。
更新
数组索引的 C++17 规范如下:
constexpr reference operator[](size_type n);
constexpr const_reference operator[](size_type n) const;
循环现在完成。Universe 可以在编译时计算。;-)