//******************************************************** // The following code example is taken from the book // C++23 - The Complete Guide // by Nicolai M. Josuttis (www.josuttis.com) // http://www.cppstd23.com // // The code is licensed under a // Creative Commons Attribution 4.0 International License // http://creativecommons.org/licenses/by/4.0/ //******************************************************** #include #include #include #include template requires (SZ1 > 0 && SZ2 > 0) class Array2D { std::array data = {}; public: Array2D() = default; Array2D(auto... args) : data{args...} { } // read access for two dimensions: const auto& @\TB{operator[]}@ (int x, int y) const { if (x < 0 || x >= SZ1) { throw std::out_of_range{"invalid row " + std::to_string(x)}; } if (y < 0 || y >= SZ2) { throw std::out_of_range{"invalid column " + std::to_string(x)}; } return data[x * SZ2 + y]; } // write access for two dimensions: auto& @\TB{operator[]}@ (int x, int y) { if (x < 0 || x >= SZ1) { throw std::out_of_range{"invalid row " + std::to_string(x)}; } if (y < 0 || y >= SZ2) { throw std::out_of_range{"invalid column " + std::to_string(x)}; } return data[x * SZ2 + y]; } void print() const { std::println("{}", data); } };