c++ - 使用 CRTP 创建特征矩阵

标签 c++ templates eigen crtp

我有一个类层次结构,其中包含一些特征矩阵作为成员,但它们的大小取决于派生类。我希望能够在基类中声明矩阵,但具有从派生类中使用的大小。我以为我可以为此使用 CRTP,但我不确定我是否正确使用了它。这是我试过的代码

template<typename T>
class Base {
public:
    const int matSize = static_cast(T*)(this)->_matSize;
    Eigen::Matrix<int, matSize, mastSize> Mat = Eigen::Matrix<int, matSize, matSize>::Zero();

    virtual void print() { std::cout << Mat << std::endl; };
};

class Derived1 : public Base<Derived1>{
public:
    const int _matSize = 3;
};

class Derived2 : public Base<Derived2>{
public:
    const int _matSize = 4;
};

int main(){
    Derived1 d1;
    d1.print();   // print a 3x3 zero matrix

    Derived2 d2;
    d2.print();   // print a 4x4 zero matrix

    std::cin.get();
    return 0;
}

但是,这是行不通的。有没有办法实现这样的目标?

编辑:

这样做的主要原因是我有一些函数可以执行一些矩阵代数,无论大小如何。所以我希望能够在不同派生类的对象上调用该函数,并且能够使用相同的函数而不是为每个矩阵大小使用单独的函数。

还有一个接口(interface),任何 Base 类型的对象都将有一个矩阵 Mat,其大小将取决于它是从哪个 Base 的派生类创建的。

最佳答案

正如我在评论中所说,确实没有理由仅针对您所指出的内容使用 CRTP,但是如果您出于其他原因设置此模式,则类似以下的内容应该有效(我没有 Eigen::Matrix 可用,因此我为编译器删除了必要的接口(interface)):

#include <iostream>

namespace Eigen {
    template<typename T, int W, int H>
    class Matrix {
    public:
        static Matrix<T,W,H> Zero() {
            return Matrix<T, W, H>{};
        }

        std::ostream &print_on(std::ostream &strm) const {
            return strm;
        }
    };
}

template <typename T, int W, int H>
std::ostream &operator<<(std::ostream &strm, Eigen::Matrix<T,W,H> const &matrix) {
    return matrix.print_on(strm);
}

template<typename T, int S>
class Base {
public:
    Eigen::Matrix<int, S, S> Mat = Eigen::Matrix<int, S, S>::Zero();

    virtual void print() { std::cout << Mat << std::endl; };
};

class Derived1 : public Base<Derived1,3>{
public:
};

class Derived2 : public Base<Derived2,4>{
public:
};

template <int Size>
class AdvertisingDerived : public Base<AdvertisingDerived<Size>,Size> {
public:
    constexpr static int matrixSize = Size;
};

int main(){
    Derived1 d1;
    d1.print();   // print a 3x3 zero matrix

    Derived2 d2;
    d2.print();   // print a 4x4 zero matrix

    AdvertisingDerived<3> ad1;

    AdvertisingDerived<4> ad2;

    std::cin.get();
    return 0;
}

关于c++ - 使用 CRTP 创建特征矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54499413/

相关文章:

c++ - 在 MacOSX 上,使用 g++,std::vector .size() 线程安全吗?

c++ - 带模板的容器声明

带有智能指针的 C++ 智能 vector ?

C++实现模板类时编译错误

c++ - 使用条件语句在运行时选择不同的模板化矩阵类

matrix - 非正定矩阵的 Eigen 共轭梯度

c++ - C/C++ : How to convert 6bit ASCII to 7bit ASCII

c++ - 从模板成员类型派生模板化类的成员变量类型

c++ - 将绑定(bind)函数分配给 std::function

gcc - Eigen 和 GCC 5:不推荐使用类 std::binder2nd