Я пытаюсь заполнить 2D-массив во время компиляции заданной функцией. Вот мой код:
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
правильно заполняется во время компиляции.
Однако, если я изменяю простой 2D-массив 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
? Если С++ 14 позволяет нам изменять переменные, объявленные в области constexpr
, почему это не поддерживается std::array
?
Раньше я думал, что std::array
как обычный массив, только лучше. Но вот пример, где я могу использовать простой массив, но не могу использовать std::array
.