I have been trying to figure out expression templates since the last couple of days but haven't been able to get past this. I am building a matrix starting with the add operator. I am building using c++14. My matrix.h looks like this:
template <typename T, std::size_t COL, std::size_t ROW>
class Matrix {
public:
using value_type = T;
Matrix() : values(COL * ROW) {}
static size_t cols() { return COL; }
static size_t rows() { return ROW; }
const T& operator()(size_t x, size_t y) const { return values[y * COL + x]; }
T& operator()(size_t x, size_t y) { return values[y * COL + x]; }
template <typename E>
Matrix<T, COL, ROW>& operator=(const E& expression) {
for (std::size_t y = 0; y != rows(); ++y) {
for (std::size_t x = 0; x != cols(); ++x) {
values[y * COL + x] = expression(x, y);
}
}
return *this;
}
private:
std::vector<T> values;
};
template <typename LHS, typename RHS>
class MatrixSum
{
public:
using value_type = typename LHS::value_type;
MatrixSum(const LHS& lhs, const RHS& rhs) : rhs(rhs), lhs(lhs) {}
value_type operator() (int x, int y) const {
return lhs(x, y) + rhs(x, y);
}
private:
const LHS& lhs;
const RHS& rhs;
};
template <typename LHS, typename RHS>
MatrixSum<LHS, RHS> operator+(const LHS& lhs, const LHS& rhs) {
return MatrixSum<LHS, RHS>(lhs, rhs);
}
Cpp file main function looks contains this:
Matrix<int,5,5>mx,my;
mx+my;
This shows the following error:
invalid operands to binary expression ('Matrix<int, 5, 5>' and 'Matrix<int, 5, 5>')
mx+my;
I have searched a lot online, but I clearly have missed something. The above code is taken from https://riptutorial.com/cplusplus/example/19992/a-basic-example-illustrating-expression-templates. I would appreciate if some resources to understand expression templates can be shared.