gpt4 book ai didi

c++ - 使用 C++ 模板更改操作

转载 作者:行者123 更新时间:2023-11-28 04:31:40 25 4
gpt4 key购买 nike

这可能是一个重复的问题,但我不确定如何搜索它,而且我还找不到任何东西。假设我有两个类:

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); }
...
}

两个类中的所有函数都相同,但第二个类仅处理对角矩阵,因此它们可以存储为 vector 。是否可以将这两个类合并为一个类,例如使用模板来选择变量类型和相应的操作(矩阵或分量乘法)?

最佳答案

使用 Curiously Recurring Template Pattern (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); }
};

关于c++ - 使用 C++ 模板更改操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52728120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com