c++ - 使用 C++ 模板更改操作
问题描述
这可能是一个重复的问题,但是我不知道如何搜索它,我还找不到任何东西。假设我有两个类,如下所示:
class MyMatrix : public MyAbstract {
using MatrixType = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>;
MatrixType A, B;
public:
...
MatrixType product() { return A * B; }
...
}
和
class MyDiagonal : public MyAbstract {
using VectorType = Eigen::Matrix<double, Eigen::Dynamic, 1>;
VectorType A, B;
public:
...
VectorType product() { return A.cwiseProduct(B); }
...
}
两个类中的所有函数都是相同的,但第二类只处理对角矩阵,因此可以将它们存储为向量。是否可以将这两个类合并为一个,例如使用模板来选择变量的类型和相应的操作(矩阵或分量乘法)?
解决方案
使用奇怪重复的模板模式 (CRTP):
template <typename Derived>
class MyMatrixLikeThing : public MyAbstract {
public:
void do_something() const {
// How to access members of Derived:
static_cast<Derived const&>(*this).A;
static_cast<Derived const&>(*this).B;
static_cast<Derived const&>(*this).product();
}
// Other functions
};
class MyMatrix : public MyMatrixLikeThing<MyMatrix> {
friend MyMatrixLikeThing<MyMatrix>; // so that it can access private members
using MatrixType = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>;
MatrixType A, B;
public:
MatrixType product() const { return A * B; }
};
class MyDiagonal : public MyMatrixLikeThing<MyDiagonal> {
friend MyMatrixLikeThing<MyDiagonal>; // so that it can access private members
using VectorType = Eigen::Matrix<double, Eigen::Dynamic, 1>;
VectorType A, B;
public:
VectorType product() const { return A.cwiseProduct(B); }
};
推荐阅读
- python - 如何在 Python 中的某个时间后循环结束请求?
- svn - 如何为团队成员隐藏 subversion 中的子文件夹
- javascript - 一键提交两份表格
- ios - A-frame 图像在移动 ios Safari 的反应中未正确加载。我得到一个黑盒子而不是图像
- javascript - 如何在数组中获取数组中的“列”数?
- ios - 允许 IOS Webview 通过轮询网络调用在后台运行
- compiler-errors - 我的 Pascal 程序警告我有关无法访问的代码
- javascript - 在 div 中使用鼠标滚轮和按钮进行水平滚动
- c++ - 至少出现两次的最长子串
- javascript - 我怎样才能延迟setActivity