corwin corwin - 2 years ago 108
C++ Question

overload () operator for multidimensional data access

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?

Answer Source

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];
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download