我正在编写一个可以同时支持行和列主要存储的矩阵模板类。理想情况下,我只想专门研究受存储格式影响的方法。但是,当我尝试专门化一种方法(如下所示)时,我只收到错误消息。
enum MatrixStorage
{
ColumnMajor,
RowMajor
};
template< typename T,
unsigned rows,
unsigned columns,
MatrixStorage storage = ColumnMajor >
class Matrix
{
public:
T & operator () ( unsigned const & row, unsigned const & column );
};
template< typename T,
unsigned rows,
unsigned columns >
T & Matrix< T, rows, columns, ColumnMajor >::
operator () ( unsigned const & row, unsigned const & column )
{
return elements[ ( row + ( rows * column ) ) % ( rows * columns ) ];
}
template< typename T,
unsigned rows,
unsigned columns >
T & Matrix< T, rows, columns, RowMajor >::
operator () ( unsigned const & row, unsigned const & column )
{
return elements[ ( ( row * columns ) + column ) % ( rows * columns ) ];
}
错误输出:
error C3860: template argument list following class template name must list parameters in the order used in template parameter list
error C2976: 'maths::Matrix<T,rows,columns,storage>' : too few template arguments
error C3860: template argument list following class template name must list parameters in the order used in template parameter list
按照其他问题中给出的示例,看起来语法是正确的。尽管如此,我能做到这一点的唯一方法是专门化类本身(如下所示),但这意味着复制所有不依赖于存储格式的方法。
enum MatrixStorage
{
ColumnMajor,
RowMajor
};
template< typename T,
unsigned rows,
unsigned columns,
MatrixStorage storage = ColumnMajor >
class Matrix;
template< typename T,
unsigned rows,
unsigned columns >
class Matrix< T, rows, columns, ColumnMajor >
{
T & operator () ( unsigned const & row, unsigned const & column );
};
template< typename T,
unsigned rows,
unsigned columns >
class Matrix< T, rows, columns, RowMajor >
{
T & operator () ( unsigned const & row, unsigned const & column );
};
不能部分专用化函数模板,这些模板包括模板的成员函数。替代方法是创建一个提供所需功能的模板帮助程序类,然后将对类模板的调用从模板的成员函数转发。
或者,由于您的用例非常简单,您可以编写一个帮助程序函数(无论是否模板,都不需要它是一个完整的类),该函数将为您提供给定坐标和模式的数组中的索引。
template <MatrixStorage m>
int index_of( int row, int col, int rows, int columns ) {
return ( row + ( rows * column ) ) % ( rows * columns );
}
template <>
int index_of<RowMajor>( int row, int col, int rows, int columns ) {
return ( ( row * columns ) + column ) % ( rows * columns );
}
您可以通过获取将在运行时检查的 MatrixStorage
类型的额外参数(简单if
)来使其成为非模板