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.
This lets you take a lambda, and produce an indexer (with
[]
support).Suppose you have an
operator()
that supports passing both coordinates at onxe as two arguments. Now writing[][]
support is just:And done. No custom class required.
You can overload
operator[]
to return an object on which you can useoperator[]
again to get a result.Then you can use it like:
This is just a simple example, you'd want to add a bunch of bounds checking and stuff, but you get the idea.
An expression
x[y][z]
requires thatx[y]
evaluates to an objectd
that supportsd[z]
.This means that
x[y]
should be an object with anoperator[]
that evaluates to a "proxy object" that also supports anoperator[]
.This is the only way to chain them.
Alternatively, overload
operator()
to take multiple arguments, such that you might invokemyObject(x,y)
.Sample code:
It is possible if you return some kind of proxy class in first [] call. However, there is other option: you can overload operator() that can accept any number of arguments (
function(3,3)
).vector< vector< T > > or T** is required only when you have rows of variable length and way too inefficient in terms of memory usage/allocations if you require rectangular array consider doing some math instead! see at() method: