As others have pointed out, there is no [][]
operator, it's a []
operator applied to the results of a []
operator. In the most general
case, the first []
operator will return a proxy, which implements
itself a []
operator. In the simplest case, the “proxy”
can be a T*
, since in C++, pointers implement the []
operator. A
more generic implementation might be along the lines of:
class ElementProxy
{
Container* myOwner;
int myRowIndex;
int myColumnIndex;
public:
ElementProxy( Container* owner, int rowIndex, int columnIndex )
: myOwner( owner )
, myRowIndex( rowIndex )
, myColumnIndex( columnIndex )
{
}
operator Type() const // lvalue to rvalue conversion
{
return myOwner->get( myRowIndex, myColumnIndex );
}
void operator=( Type const& rhs ) const
{
myOwner->set( myRowIndex, myColumnIndex, rhs );
}
};
class RowProxy
{
public:
RowProxy( Container* owner, int rowIndex )
: myOwner( owner )
, myRowIndex( rowIndex )
{
}
ElementProxy operator[]( int columnIndex ) const
{
return ElementProxy( myOwner, myRowIndex, columnIndex );
}
};
This isn't perfect; if you are dealing with class types, it's impossible
to support something line container[i][j].x
, for example; we can't
overload operator.
. If you need to support this, about the best you
can do is overload operator->
on the ElementProxy
, and require
client code to use ->
instead of .
, even though it's not really a
pointer, smart or otherwise.