2

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]
3
  • 9
    fooObject.matrix[ 0, 0, 0 ] -> fooObject[ 0, 0, 0 ]. Voting to close as a typo. Commented May 10, 2022 at 7:44
  • @HolyBlackCat Oh my bad. So is my solution correct? And how should I implement it for const objects? Commented May 10, 2022 at 7:46
  • 1
    "And how should I implement it for const objects": you should ask a new question for this: Commented May 10, 2022 at 7:47

1 Answer 1

2
fooObject[ 0, 0, 0 ] = 5;

not

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

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.