作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在我的程序中实现矩阵。方阵应该有额外的能力,比如计算行列式,但它们也应该有矩阵的所有能力。我试过这样做 - 部分专门化 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_impl
和 special_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/
我是一名优秀的程序员,十分优秀!