//********************************************************
// The following code example is taken from the book
//  C++23 - The Complete Guide
//  by Nicolai M. Josuttis (www.josuttis.com)
//  https://www.cppstd23.com
//
// The code is licensed under a
//  Creative Commons Attribution 4.0 International License
//  https://creativecommons.org/licenses/by/4.0/
//********************************************************


#include <print>
#include <array>
#include <exception>
#include <string>

template<typename T, int SZ1, int SZ2>
requires (SZ1 > 0 && SZ2 > 0)
class Array2D 
{
  std::array<T, SZ1 * SZ2> data = {};
 public:
  Array2D() = default;
  Array2D(auto... args)
   : data{args...} {   
  }

  // read access for two dimensions:   
  const auto& 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(y)};
    }
    return data[x * SZ2 + y];
  }

  // write access for two dimensions:   
  auto& 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(y)};
    }
    return data[x * SZ2 + y];
  }

  void print() const {
    std::println("{}", data);
  }
};

