Is it possible to overload []
operator twice? To allow, something like this: function[3][3]
(like in a two dimensional array).
If it is possible, I would like to see some example code.
Is it possible to overload []
operator twice? To allow, something like this: function[3][3]
(like in a two dimensional array).
If it is possible, I would like to see some example code.
Using C++11 and the Standard Library you can make a very nice two-dimensional array in a single line of code:
By deciding the inner matrix represents rows, you access the matrix with an
myMatrix[y][x]
syntax:And you can use ranged-
for
for output:(Deciding the inner
array
represents columns would allow for anfoo[x][y]
syntax but you'd need to use clumsierfor(;;)
loops to display output.)My 5 cents.
I intuitively knew I need to do lots of boilerplate code.
This is why, instead of operator [], I did overloaded operator (int, int). Then in final result, instead of m[1][2], I did m(1,2)
I know it is DIFFERENT thing, but is still very intuitive and looks like mathematical script.
Have you got any idea about what
function
,function[x]
andfunction[x][y]
mean?First take a look at where
function
is defined. Maybe there is some declaration or definition likeSomeClass function;
(Because you said that it's operator overload, I think you won't be interested at array like
SomeClass function[16][32];
)So
function
is an instance of typeSomeClass
. Then look up declaration ofSomeClass
for the return type ofoperator[]
overload, just likeReturnType operator[](ParamType);
Then
function[x]
will have the typeReturnType
. Again look upReturnType
for theoperator[]
overload. If there is such a method, you could then use the expressionfunction[x][y]
.Note, unlike
function(x, y)
,function[x][y]
is 2 separated calls. Neither compiler nor runtime garantees the atomicity. Another similar example is, libc saysprintf
is atomic while successively calls to the overloadedoperator<<
in output stream are not. A statement likestd::cout << "hello" << std::endl;
might have problem in multi-thread application, but something like
printf("%s%s", "hello", "\n");
is OK.
In conclusion, though C++ is able to offer such a syntactic sugar for you, it is not the recommended way to program.
One approach is using
std::pair<int,int>
:Of course, you may
typedef
thepair<int,int>
If, instead of saying a[x][y], you would like to say a[{x,y}], you can do like this: