I have the following code:
#include <iostream>
#include <vector>
template<typename T> class Matrix {
public:
int rows;
int cols;
std::vector<T> data;
Matrix(): rows(0), cols(0), data(std::vector<T>()){};
Matrix(const int rows, const int cols): rows(rows), cols(cols), data(std::vector<T>(rows*cols)){};
Matrix(const int rows, const int cols, std::vector<T> data): rows(rows), cols(cols), data(data){};
T& operator()(int row, int col)
{
return data.at(row * cols + col);
}
};
int main() {
Matrix<int> matrix_int(2,2);
Matrix<bool> matrix_bool(2,2);
matrix_int(0,0) = 5; // This works
matrix_bool(0,0) = true; // This does not work
std::cout << matrix_int(0,0) << std::endl;
std::cout << matrix_bool(0,0) << std::endl;
return 0;
}
Accessing elements in matrix_int works, but not matrix_bool, I get the following error:
/test/simple_example.cpp: In instantiation of ‘T& Matrix<T>::operator()(int, int) [with T = bool]’:
/test/simple_example.cpp:25:20: required from here
/test/simple_example.cpp:16:40: error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’
16 | return data.at(row * cols + col);
| ^
In file included from /usr/include/c++/9/vector:68,
from /test/simple_example.cpp:2:
/usr/include/c++/9/bits/stl_bvector.h:86:5: note: after user-defined conversion: ‘std::_Bit_reference::operator bool() const’
86 | operator bool() const _GLIBCXX_NOEXCEPT
| ^~~~~~~~
What could be the issue here? Is there some difference between the references returned by std::vector<int>::at and std::vector<bool>::at?
I've noticed that accessing elements in a vector directly works, for example:
std::vector<bool> v(4);
v.at(0) = true;
But I don't understand what the difference is between this and the previous example.