C++ [] array operator with multiple arguments?

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;

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.


Prior to C++23, you could not overload operator[] to accept multiple arguments. As a workaround, you instead can overload operator(). (See How do I create a subscript operator for a Matrix class? from the C++ FAQ.)


From C++23, as mentioned in a (deleted) answer by cigien, multiple subscript arguments can be passed to operator[] directly. See this demo from the cppreference page.


For completeness sake: There is a way to actually use the bracket operator with multiple arguments, if they are not basic data types, namely by overloading the comma operator and not the bracket operator, see the following post about comma overloading:

https://stackoverflow.com/a/18136340/5836981

Disclaimer: in my opinion overloading the comma operator is error prone and renders code more obscure, and is worth considering only in more exotic cases. I added this answer because I came over an instance of this in some code and it took me a while to figure out that the key was not the [] operator (which cannot be overloaded with multiple arguments) but the ,operator.