Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Matrix Class with Operator Overloading

Tags:

c++

operators

I was implementing a small dense matrix class and instead of plan get/set operators I wanted to use operator overloading to make the API more usable and coherent.

What I want to achieve is pretty simple:

template<typename T>
class Matrix
{
public:

    /* ... Leaving out CTOR and Memory Management for Simplicity */

    T operator() (unsigned x, unsigned y){/* ... */ }
};


Matrix<int> m(10,10);
int value = m(5,3); // get the value at index 5,3
m(5,3) = 99; // set the value at index 5,3

While getting the value is straight forward by overloading operator(), I can't get my head around defining the setter. From what I understood the operator precedence would call operator() before the assignment, however it is not possible to overload operator() to return a correct lvalue.

What is the best approach to solve this problem?

like image 348
grundprinzip Avatar asked Jun 06 '26 03:06

grundprinzip


1 Answers

I dispute that "it's not possible" to do the correct thing:

struct Matrix
{
  int & operator()(size_t i, size_t j) { return data[i * Cols + j]; }
  const int & operator()(size_t i, size_t j) const { return data[i * Cols + j]; }

  /* ... */

private:
  const size_t Rows, Cols;
  int data[Rows * Cols];  // not real code!
};

Now you can say, m(2,3) = m(3,2) = -1; etc.

like image 133
Kerrek SB Avatar answered Jun 07 '26 19:06

Kerrek SB