0

like in the title, here is a pice of code:

class matrix{
    std::vector<std::vector<bool>> base;
    std::pair<int, int> size;
public:
    matrix(int x, int y){
        size.first = x; size.second = y;
        std::vector<std::vector<bool>> b(x, std::vector<bool>(y));
        base = b;
    }
    bool& operator ()(int x, int y) const {
        if(x < 0 || y < 0 || x >= size.first || y >= size.second){outOfBounds ex; throw ex;}
        return base[x][y];
    }
    /*and more that is unrelated to the question*/
};

the error is in bool& operator(...) and it is as follows:

cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type‘std::vector<bool>::const_reference’ {aka ‘bool’}
   30 |                 return base[x][y];

in the code, the size of the vector (matrix) dose not change

I also replaced bool with int and its the same problem, can't convert from int to int&

The function can't be const, so that the value of the reference can be changed

1 Answer 1

2
bool& operator ()(int x, int y) const {

The const at the end means that this is a constant class method, and this is constant.

return base[x][y];

Everything in this is constant. Including this. The return value from this operator overload should, therefore, be const bool & instead of bool &.

If after understanding this you go back and reread your compiler's error message it should now make perfect sense to you, because that's exactly what your compiler was telling you.

Alternatively you can drop the const from the overloaded operator declaration, and return a bool &, that's up to you.

But then, you're going to wind up with another, special problem: a std::vector<bool> is not really a vector of bools, but something very weird.

So, the final solution may be to simply declare the return value as an auto &, and let the compiler figure it out for you. ...You don't really want to know what it really is.

Sign up to request clarification or add additional context in comments.

2 Comments

after dropping the const from the function declaration the message is as follows: ``` error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’ 30 | return base[x][y]; ```
Yes, that's another problem, std::vector<bool> is not really a vector of bools. Updated my answer to suggest declaring the return value as an auto &.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.