C++ [] array operator with multiple arguments?
Nope, you can't overload operator[]
to accept multiple arguments. You instead can overload operator()
. See How do I create a subscript operator for a Matrix class? from the C++ FAQ.
It is not possible to overload the []
operator to accept multiple arguments, but an alternative is to use the proxy pattern.
In two words: a[x][y]
, the first expression (a[x]
) would return a different type, named proxy type, which would have another operator[]
. It would call something like _storedReferenceToOriginalObject->At(x,y)
of the original class.
You will not be able to do a[x,y]
, but I guess you wanted to overload the usual C++-style 2D array syntax anyway.
There's a nice little trick you can do with the uniform initialization syntax available in C++11. Instead of taking the index directly, you take a POD.
struct indices{ std::size_t i, j, k;};T& operator[](indices idx){ return m_cells[idx.k * m_resSqr + idx.j * m_res + idx.i];}
And then use the new syntax:
my_array<int> arr;// ...arr[{1, 2, 3}] = 42;