How to implement `opIndex` in higher dimensions?

struct M{ T opIndex(uint i){ ... } } 

which gives me this:

 m[i] 

but what if I want it in two dimensions so that I can:

 m[i][j] 

Is there any way to do this?

+7
source share
1 answer

Yes, you can do a C ++ way to return a temporary object (the structure is best in case of D), which also has an overload of the index operator.

But the best idea in D is to look for the syntax m[i, j] :

 struct S { uint opIndex(uint i, uint j) { return i + j; } } void main() { S s; assert(s[2, 3] == 5); } 

If you still want to use m[i][j] , the nested structure gives you the syntax output:

 struct S { auto opIndex(uint i) { struct Temp { uint opIndex(uint j) { return i + j; } } return Temp(); } } void main() { S s; assert(s[2][3] == 5); } 
+8
source

All Articles