【问题标题】:Change operation with C++ template使用 C++ 模板更改操作
【发布时间】:2019-03-14 15:37:00
【问题描述】:

这可能是一个重复的问题,但是我不知道如何搜索它,我还找不到任何东西。假设我有两个看起来像这样的类:

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,所以我需要更多地了解这个。但我只需要减少重复(不必用两种不同的产品将所有功能写两次),而不影响效率。

标签: c++ class templates operators


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2013-04-11
    • 2014-12-10
    相关资源
    最近更新 更多