Search code examples
c++c++14operator-overloading

Is there a way I could overload operator[] with multiple parameters?


I have the following code, and it is giving following error: binary 'operator [' has too many parameters

template <typename T>
struct Test {
public:
    T operator[](int x, int y) {
        //...
    }
};

Is there a way I could overload the [] operator with multiple parameters?


Solution

  • You need C++23 to overload operator[] with multiple parameters. Before that you can use a named function:

    template <typename T>
    struct Test {
    public:
        T get(int x, int y) {
            //...
        }
    };
    

    or operator() which can be overloaded with arbitrary number of parameters.

    PS: If you are like me then you will wonder how that change (only one parameter allowed -> any number allowed) was possible in the presence of the comma operator. The way this is fine is that since C++23 you need parenthesis to call the comma operator (ie a[b,c] never calls operator,(b,c), while a[(b,c)] does, see https://en.cppreference.com/w/cpp/language/operator_other).