gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:42:17 29 4
gpt4 key购买 nike

我正在尝试在我的程序中实现矩阵。方阵应该有额外的能力,比如计算行列式,但它们也应该有矩阵的所有能力。我试过这样做 - 部分专门化 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/

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