C++ [] array operator with multiple arguments?

Viewed 37149

Can I define in C++ an array operator that takes multiple arguments? I tried it like this:

const T& operator[](const int i, const int j, const int k) const{ 
    return m_cells[k*m_resSqr+j*m_res+i];
}

T& operator[](const int i, const int j, const int k){ 
    return m_cells[k*m_resSqr+j*m_res+i];       
}

But I'm getting this error:

error C2804 binary operator '[' has too many parameters
6 Answers

It is not possible to overload the [] operator to accept multiple arguments, but an alternative is to use the proxy pattern.

In two words: a[x][y], the first expression (a[x]) would return a different type, named proxy type, which would have another operator[]. It would call something like _storedReferenceToOriginalObject->At(x,y) of the original class.

You will not be able to do a[x,y], but I guess you wanted to overload the usual C++-style 2D array syntax anyway.

Edit: as pointed in comment, in C++20 operator comma will be deprecated, so as the answer below.

You can't overload operator[], but you can fake it by overloading operator, instead.

Following your code it becomes:

T& operator,(const int i, const int j, const int k){ 
    return m_cells[k*m_resSqr+j*m_res+i];       
}

now you'll be able to call

something[1, 2, 3]

You can extend it using templates, templates with variadic arguments, std::pair or std::tuple depending on your use case and C++ version

Related