0

I want to have access to multidimensional data inside a class, I found:

To provide multidimensional array access semantics, e.g. to implement a 3D array access a[i][j][k] = x;, operator[] has to return a reference to a 2D plane, which has to have its own operator[] which returns a reference to a 1D row, which has to have operator[] which returns a reference to the element. To avoid this complexity, some libraries opt for overloading operator() instead, so that 3D access expressions have the Fortran-like syntax a(i, j, k) = x;

on http://en.cppreference.com/w/cpp/language/operators

and I'd like to use suggested syntax, but I have trouble implementing that. How can I write overloaded assignment operator to work that way?

corwin
  • 77
  • 10

2 Answers2

3

For example, it would be

template <typename T, std::size_t S1, std::size_t S2, S3>
struct Matrix3D
{
    // ...

     const T& operator()(std::size_t i, std::size_t j, std::size_t k) const {
          return data[i][j][k];
     }
     T& operator()(std::size_t i, std::size_t j, std::size_t k) {
          return data[i][j][k];
     }
private:
    T data[S1][S2][S3];
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

Thanks to your help I have a solution:

T& operator()(unsigned width, unsigned height) {
    return my_data[width + height * data_width];
}

works both ways:

my_class(1,2) = value;
value = my_class(1,2);
corwin
  • 77
  • 10