【发布时间】:2016-03-15 23:07:35
【问题描述】:
我正在尝试使用给定函数在编译时填充二维数组。这是我的代码:
template<int H, int W>
struct Table
{
int data[H][W];
//std::array<std::array<int, H>, W> data; // This does not work
constexpr Table() : data{}
{
for (int i = 0; i < H; ++i)
for (int j = 0; j < W; ++j)
data[i][j] = i * 10 + j; // This does not work with std::array
}
};
constexpr Table<3, 5> table; // I have table.data properly populated at compile time
它工作得很好,table.data 在编译时被正确填充。
但是,如果我将纯二维数组 int[H][W] 更改为 std::array<std::array<int, H>, W>,我会在循环体中出现错误:
error: call to non-constexpr function 'std::array<_Tp, _Nm>::value_type& std::array<_Tp, _Nm>::operator[](std::array<_Tp, _Nm>::size_type) [with _Tp = int; long unsigned int _Nm = 3ul; std::array<_Tp, _Nm>::reference = int&; std::array<_Tp, _Nm>::value_type = int; std::array<_Tp, _Nm>::size_type = long unsigned int]'
data[i][j] = i * 10 + j;
^
Compilation failed
显然,我试图调用std::array::operator[] 的非常量重载,而不是constexpr。问题是,为什么不是constexpr?如果 C++14 允许我们修改在 constexpr 范围内声明的变量,为什么 std::array 不支持?
我曾经认为std::array 就像普通数组一样,只是更好。但这里有一个例子,我可以使用普通数组,但不能使用std::array。
【问题讨论】:
-
看起来像是标准中的疏忽。
-
一旦您使用索引 std::integer_sequence 习惯用法定义了从 C 样式数组到 std::array 的 constexpr 转换,它对 C++14 中的 constexpr 元编程非常有帮助。
标签: c++ arrays c++14 constexpr