首页 > 解决方案 > 使用表达式模板在矩阵中重载运算符

问题描述

自过去几天以来,我一直在尝试找出表达式模板,但一直无法克服。我正在构建一个从 add 运算符开始的矩阵。我正在使用 c++14 构建。我的 matrix.h 看起来像这样:

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 文件主函数看起来包含以下内容:

Matrix<int,5,5>mx,my;
mx+my;

这显示以下错误:

invalid operands to binary expression ('Matrix<int, 5, 5>' and 'Matrix<int, 5, 5>')
        mx+my;

我在网上搜索了很多,但我显然错过了一些东西。上面的代码取自https://riptutorial.com/cplusplus/example/19992/a-basic-example-illustrating-expression-templates。如果可以共享一些理解表达式模板的资源,我将不胜感激。

标签: c++matrixheader-filesexpression-templates

解决方案


推荐阅读