C ++ arrow for overloaded index (this & # 8594; [])

I have a simple class whose index operator I overloaded:

class dgrid{ double* data; // 1D Array holds 2D data in row-major format public: const int nx; const int ny; double* operator[] (const int index) {return &(data[index*nx]);} } 

So dgrid[x][y] works like a 2d array, but the data is contiguous in memory.

However, from inside the member functions, this is a little more awkward, I need to do something like (*this)[x][y] , which works, but seems smelly, especially when I have sections like:

 (*this)[i][j] = (*this)[i+1][j] + (*this)[i-1][j] + (*this)[i][j+1] + (*this)[i][j-1] - 4*(*this)[i][j]; 

Is there a better way to do this? Something like this->[x][y] (but this does not work). Does the small function f(x,y) returns &data[index*nx+ny] single option?

+6
source share
1 answer

You can reload →, but why not just do:

 T& that = *this; //or use auto as tc suggests that[i][j] = that[i+1][j] + that[i-1][j] + that[i][j+1] + that[i][j-1] - 4*that[i][j]; 

It (pun intended) is at least as readable as it is → [] []. No?

+5
source

Source: https://habr.com/ru/post/982799/


All Articles