How can I overload multi-dimensional brackets?
Let's say that I have a class which enables me to access points in an n-vector space. For example:
class NSpaceVector {
private:
int vectorSpace[8][8][8][8][8][8][8];
public:
const NSpaceVector operator[][][][][][][](int i, int j, int k, int l, int m, int n, int p)const {return vectorSpace[i][j][k][l][m][n][p]; }
NSpaceVector operator[][][][][][][](int i, int j, int k, int l, int m, int n, int p) {return vectorSpace[i][j][k][l][m][n][p]; }
}
unsigned long & operator [](int i) {return registers[i];}
What I would like to do is overload the bracket operator so that I can index into this location like so:
int main() {
NSpaceVector nsv; // Assume initializes all to 0
nsv[2][4][7][4][0][7][6] = 2;
cout << nsv[2][4][7][4][0][7][6] << endl; //-> 2
cout << nsv[1][4][7][4][0][7][6] << endl; //-> 0
return 0;
}
I can't get this to compile. Any ideas? Thx, Keith :^)
The standard answer is to have each
[]
(from left-to-right) return a proxy for the correct nested subset, the last of which actually returns a reference to the data. In your scheme, it would be easiest by far to template the nested types to automate production.As the mysterious user4581301 mentions, it's much simpler to provide
Sample template production of your desired class is probably simpler than using a temporary proxy object:
Note this doesn't currently default-initialize the array members, but we can use aggregate initialization anyway:
Also note that
SubSpace<8,6>
gives the 8x7 result you wanted, since Depth terminates at 0. This could be cleaned up with a toplevel wrapper, but I'm reluctant to terminate onDepth==1
instead and have everything go wrong when someone instantiatesSubSpace<0,0>
by accident.Simpler still, depending on whether you want any behaviour in your class, is this:
It's harder to alter the dimensions and feels more brittle than the template version, but it still works for the use case you provided.
There's only the option to overload the
operator[]()
for every level, and let the return types have anotheroperator[]()
overload.As mentioned in comments, such is usually solved with overloading the call
operator()
: