或者你可以制作一个这样的包装:
(一般来说,在C++中,不需要使用sizeof那么多,特别是不需要验证数组大小)
#include <array>
#include <stdexcept>
#include <iostream>
template<typename T, std::size_t ROWS, std::size_t COLS>
class array2d_t final
{
public:
array2d_t() = default;
~array2d_t() = default;
array2d_t(const array2d_t&) = default;
array2d_t& operator=(const array2d_t&) = default;
array2d_t(array2d_t&&) = default;
array2d_t& operator=(array2d_t&&) = default;
explicit array2d_t(const int (&values)[ROWS][COLS])
{
std::size_t offset{0};
for(std::size_t row{0ul}; row < ROWS; ++row)
{
for(std::size_t col{0ul}; col < COLS; ++col, ++offset)
{
m_values[offset] = values[row][col];
}
}
}
auto& at(std::size_t row, std::size_t col)
{
if ((row >= ROWS) || (col >= COLS)) throw std::invalid_argument{ "index out of range" };
std::size_t offset = (COLS*row) + col;
return m_values[offset];
}
const auto& operator()(std::size_t row, std::size_t col) const noexcept
{
std::size_t offset = (COLS*row) + col;
return m_values[offset];
}
const auto& at(std::size_t row, std::size_t col) const
{
if ((row >= ROWS) || (col >= COLS)) throw std::invalid_argument{ "index out of range" };
return operator()(row,col);
}
constexpr std::size_t rows() const noexcept { return ROWS;};
constexpr std::size_t columns() const noexcept { return COLS;};
private:
std::array<T,ROWS*COLS> m_values;
};
int main()
{
array2d_t<int,2,2> matrix{{{0,1},{2,3}}};
}