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.
Found my own simple solution to this.
For a two dimensional array, specifically, you might get away with a single operator[] overload that returns a pointer to the first element of each row.
Then you can use the built-in indexing operator to access each element within the row.
It is possible to overload multiple [] using a specialized template handler. Just to show how it works :
And now the definition of
SubscriptHandler<ClassType,ArgType,RetType,N>
to make the previous code work. It only shows how it can be done. This solution is optimal nor bug-free (not threadsafe for instance).With a
std::vector<std::vector<type*>>
, you can build the inside vector using custom input operator that iterate over your data and return a pointer to each data.For example:
Live example
This solution has the advantage of providing you with a real STL container, so you can use special for loops, STL algorithms, and so on.
However, it does create vectors of pointers, so if you're using small datastructures such as this one you can directly copy the content inside the array.
You can use a proxy object, something like this: