我想对模板类使用部分专业化,以便该模板类的所有子级都将使用该专业化。让我用一个例子来解释一下:)
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;
}