c++ - 如何在不引起递归的情况下使模板特化继承泛型基类?

标签 c++ templates matrix

我正在尝试在我的程序中实现矩阵。方阵应该有额外的能力,比如计算行列式,但它们也应该有矩阵的所有能力。我试过这样做 - 部分专门化 Matrix 并使其继承自通用 Matrix。我在 Internet 上搜索过,但没有找到类似的内容,仅适用于类型,但不适用于非类型参数。

#include <iostream>

template <int a, int b>
class Matrix {
public:
    // some functions
    void g () {
        std::cout << "hi" << std::endl;
    }
};

template <int a>
class Matrix <a, a> : public Matrix <a,a> {
public:
    void f () {
        std::cout << "hello" << std::endl;
    }
};

int main () {
    Matrix <3,3> m;
    m.f();
   m.g();
}

Matrix 实际上试图从自身继承,但出现错误

recursive type 'Matrix' undefined | aggregate 'Matrix<3, 3> m' has incomplete type and cannot be defined

最佳答案

你不能只用一个模板类来做到这一点。需要第二个模板类和一些元编程来执行如下操作:

#include <iostream>

template <int a, int b>
class Matrix_impl {
public:
    // some functions
    void g () {
        std::cout << "hi" << std::endl;
    }
};

template <int a>
class special_matrix_impl : public Matrix_impl<a,a> {
public:
    void f () {
        std::cout << "hello" << std::endl;
    }
};

template<int a, int b>
struct which_template {

    typedef Matrix_impl<a, b> type;
};

template<int a>
struct which_template<a, a> {

    typedef special_matrix_impl<a> type;
};

template<int a, int b>
using Matrix=typename which_template<a, b>::type;

int main () {
    Matrix <3,3> m;
    m.f();
    m.g();
}

这里真正的模板名称是Matrix_implspecial_matrix_impl , 和 Matrix<a,b>选择合适的。

或者,使用单个模板执行此操作的唯一方法是使用额外的默认模板参数来消除模板特化的歧义:

#include <iostream>

template <int a, int b, typename=void>
class Matrix {
public:
    // some functions
    void g () {
        std::cout << "hi" << std::endl;
    }
};

template <int a>
class Matrix <a, a, void> : public Matrix <a, a, int> {
public:
    void f () {
        std::cout << "hello" << std::endl;
    }
};

int main () {
    Matrix <3,3> m;
    m.f();
   m.g();
}

有点难看,但如果需要多个特化,最终可能会变得更干净。

关于c++ - 如何在不引起递归的情况下使模板特化继承泛型基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53581750/

相关文章:

c++ - 使用 std::cout 和 std::stringstream 时,如何使符号出现在填充的末尾?

c++ - sizeof 和函数模板 : sizeof(&f) vs sizeof(&f<int>)

c++ - SFINAE 用于泛型类型的泛型操作

java - 使用 UJMP 库时如何从文件导入/导出矩阵?

c++ - 如何使用 Arduino/C++ 将整个结构传入和传出函数

c++ - 苹果操作系统 : using detachNewThreadSelector method inside a C++ class method

c++ - 从构造函数调用虚函数

templates - Dojo 构建请求已内联的模板

c++ - 矩阵中的对称位置

Ruby 核心 Matrix 与 NArray 的 NMatrix