0

I have the following code:

template<size_t rows, size_t cols>
class Matrix{
    std::array<int, rows * cols>  data;
public:
    int  operator()(size_t i, size_t j){
        return data[i * cols + j];
    }
//  ...code...
}

What is the best way to achieve this:

Matrix<1,1> a;
a(0, 0) = 0;

avoiding the lvalue required as left operand of assignment error?

dass
  • 21
  • 4

2 Answers2

3

You need to return the reference of the element from data like this:

// can change
int &operator()(size_t i, size_t j)
{
    return data[i * cols + j];
}

And every STL container includes a const function, for the cases like const Matrix &

// cannot change 
int operator()(size_t i, size_t j) const
{
    return data[i * cols + j];
}
Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23
3

You can change the following line:

int  operator()(size_t i, size_t j){

To:

int & operator()(size_t i, size_t j){

Returning a refernce (L value reference to be precise) to the element in the Matrix will allow you to assign to it.

Update: Some notes to complete my answer:

  1. As @user4581301 commented: you can see more info about C++ value categories here: What are rvalues, lvalues, xvalues, glvalues, and prvalues?
  2. As @Darth-CodeX and @HolyBlackCat mentioned, it is advisable to add a const overload for operator():
int const & operator()(int i, int j) const { /* same implementation */ }

You can use it with a const Matrix for reading elements values: if you have e.g. a Matrix const & m, you can use int val = m(0,0) to read an element value (of cource you will not be able to use it for assignment due to constness).

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • 2
    Terminology helper: [What are rvalues, lvalues, xvalues, glvalues, and prvalues?](https://stackoverflow.com/questions/3601602/what-are-rvalues-lvalues-xvalues-glvalues-and-prvalues) – user4581301 Apr 26 '22 at 17:48