Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overload [][] for a list

I got a class Matrix with a member std::list<Element> listMatrix;. Element is a a class with 3 int members line, column, value. I save in the list, elements of a matrix that are not 0 by saving the line, column and the value of the respectively element. I want to overload the operator [][] so I can do something like Matrix a; a[2][3] = 5;. I know you can't overload [][] directly.

like image 427
Ovidiu Firescu Avatar asked Jul 23 '19 11:07

Ovidiu Firescu


1 Answers

Do overload Element& operator()(int, int) (and the const variant) so you can write

matrix(2, 3) = 5;

If you absolutely need the [2][3] syntax, you'd need to define a proxy class so matrix[2] return a proxy value and proxy[3] return the desired reference. But it comes with a lot of problems. The basic idea would be:

class naive_matrix_2x2
{
    int data[4];

    struct proxy
    {
          naive_matrix_2x2& matrix;
          int x;
          int& operator[](int y) { return matrix.data[x*2+y]; }
    };
public:
    proxy operator[](int x) { return {*this, x}; }
};

Full demo: https://coliru.stacked-crooked.com/a/fd053610e56692f6

like image 109
YSC Avatar answered Oct 04 '22 09:10

YSC