我想对模板类使用部分特化,以便该模板类的所有子级都使用该特化。让我用一个例子来解释:)
template < typename T, unsigned int rows, unsigned int cols>
class BaseMatrix {...};
此类将具有指定矩阵结构的子级,例如稀疏,密集,对角线,..
template < typename T, unsigned int rows, unsigned int cols>
class DiagonalMatrix : public BaseMatrix<T,rows,cols>{..}
然后这些类将再次具有指定存储的子类:堆栈数组,向量,列表,队列,..
template < typename T, unsigned int rows, unsigned int cols>
class StackDiagonalMatrix : public DiagonalMatrix<T, rows, cols> {..}
然后是一个类 Matrix,它提供了所有的数学功能。这个模板类实现了operator+、operator-等...
template <typename T,
template<typename, unsigned, unsigned> class MatrixContainer,
unsigned Rows,
unsigned Cols>
class matrix;
对于最后一堂课,我想写这样的专业:
template <typename T,unsigned Rows, unsigned Cols>
class matrix<T, BaseMatrix, Rows, Cols> {};
template <typename T,unsigned Rows, unsigned Cols>
class matrix<T, DiagonalMatrix, Rows, Cols> {};
但是当我编写一个继承自 DiagonalMatrix 的 StackDiagonalMatrix 时,它没有找到 DiagonalMatrix 的特化——它实际上根本没有找到特化。
error: aggregate ‘matrix<int, StackDenseMatrix, 3u, 2u> matrix’ has incomplete type and cannot be defined
现在有解决这个问题的方法吗?你能为几个模板类的父类写一个特化吗?
非常感谢!
涉及的完整来源:
template <typename T, unsigned int rows, unsigned int cols>
class BaseMatrix {
protected:
BaseMatrix(){};
static const unsigned rowSize = rows;
static const unsigned colSize = cols;
};
template <typename T, unsigned int rows, unsigned int cols>
class DenseMatrix : public BaseMatrix<T, rows, cols> {
protected:
DenseMatrix(){};
};
template <typename T, unsigned int rows, unsigned int cols>
class StackDenseMatrix : public DenseMatrix<T, rows, cols> {
public:
typedef T value_type;
private:
value_type grid[rows][cols];
StackDenseMatrix();
};
template<typename value_type, unsigned int rows, unsigned int cols>
StackDenseMatrix<value_type, rows,cols>::StackDenseMatrix () {
for (unsigned int i = 0; i < this->rowSize; i++) {
for (unsigned int j = 0; j < this->colSize; j++) {
grid[i][j] = 0;
}
}
}
template <typename T, template<typename, unsigned, unsigned> class MatrixContainer ,unsigned Rows, unsigned Cols>
class matrix;
template <typename T,unsigned Rows, unsigned Cols>
class matrix<T,BaseMatrix, Rows, Cols> {
matrix(){};
};
int main () {
matrix<int, StackDenseMatrix, 3, 2> matrix;
return 0;
}