c++ - 使用表达式模板在矩阵中重载运算符
问题描述
自过去几天以来,我一直在尝试找出表达式模板,但一直无法克服。我正在构建一个从 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。如果可以共享一些理解表达式模板的资源,我将不胜感激。
解决方案
推荐阅读
- javascript - React Native 过滤器查询
- c++ - clang 编译的模块 pcm 文件有什么用?
- node.js - 如何在节点js中导入boxicons
- reactjs - 使用 redux 单击时应用和重置多个过滤器
- algorithm - 在给定偏差/比例下找到多个输入的“中间”的算法
- react-native - 在 OneSignal 中使用挂钩
- rust - 使用线程和通道的 Rust 代码恐慌
- c# - 如何修复 ASP.net MVC 项目的显示布局?
- reactjs - 无法进入 json 导致打字稿反应
- django - 在 Django Web 应用程序中上传用户图像的最佳方式是什么?