Search code examples
c++operator-overloadingsubscript-operator

Can C++'s operator[] take more than one argument?


Is it possible to define an overloaded operator[] that takes more than one argument? That is, can I define operator[] as follows:

  //In some class
  double operator[](const int a, const int b){
     return big_array[a+offset*b];}

and later use it like this?

double b=some_obj[7,3];

Solution

  • Prior to C++23 it isn't possible. You can do this from C++23.

    From cppreference:

    Since C++23, operator[] can take more than one subscripts. For example, an operator[] of a 3D array class declared as T& operator[](std::size_t x, std::size_t y, std::size_t z); can directly access the elements.

    example code from there: https://godbolt.org/z/993s5dK7z

    From C++23 draft:

    struct X {
      Z operator[](std::initializer_list<int>);
      Z operator[](auto...);
    };
    X x;
    x[{1,2,3}] = 7;                 // OK, meaning x.operator[]({1,2,3})
    x[1,2,3] = 7;                   // OK, meaning x.operator[](1,2,3)
    

    Thus, the snippets you posted will work in C++23.