首页 > 解决方案 > 使用 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); }
  ...
}

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

标签: c++classtemplatesoperators

解决方案


使用奇怪重复的模板模式 (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); }
};

推荐阅读