1

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Penny M.
  • 147
  • 10
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of relates SO posts for this. [Dupe1](https://stackoverflow.com/questions/1936399/c-array-operator-with-multiple-arguments), [Dupe2](https://stackoverflow.com/questions/7032743/can-cs-operator-take-more-than-one-argument) and [Dupe3](https://stackoverflow.com/questions/72182371/how-to-overload-the-operator-with-multiple-subscripts). – Jason Oct 19 '22 at 14:19
  • 1
    `T operator[](std::pair xy) { /*...*/ }` – Eljay Oct 19 '22 at 14:38
  • Instead, you can overload `operator()` and have people use that. – Aykhan Hagverdili Oct 19 '22 at 15:42

1 Answers1

3

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

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185