How to overload the operator[] with multiple subscripts

508 views Asked by At

C++23 added support for overloading operator[] with multiple subscripts. It's now available on GCC 12. How should one make use of it?

An example struct:

struct Foo
{
    int& operator[]( const std::size_t row,
                     const std::size_t col,
                     const std::size_t dep )
    {
        return matrix[row][col][dep];
    }

    int matrix[5][5][5];
};

I want to use it like this:

Foo fooObject;
fooObject.matrix[ 0, 0, 0 ] = 5;

But it does not compile;

error: incompatible types in assignment of 'int' to 'int [5][5]'

It also shows a warning:

warning: top-level comma expression in array subscript changed meaning in C++23 [-Wcomma-subscript]
1

There are 1 answers

0
macomphy On BEST ANSWER
fooObject[ 0, 0, 0 ] = 5;

not

fooObject.matrix[ 0, 0, 0 ] = 5;

you should also add compile option --std=c++23.