Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading