模板初始化:

Template initialization:

本文关键字:初始化      更新时间:2023-10-16

我想从Matrix类创建行向量和列向量别名。我该怎么做?

template<class T, unsigned int m, unsigned int n>
class Matrix {
public:
Matrix();

.
.
.
private:
unsigned int rows;
unsigned int cols;
.
};

我这里有错误。我看到模板的类型别名无法完成。有什么办法我能应付吗?下面我得到的错误是";别名模板的部分专用化";。

template<class T, unsigned int m, unsigned int n>
using rowVector<T,n> = Matrix<T,1,n>;
template<class T, unsigned int m, unsigned int n>
using colVector<T,m> = Matrix<T,m,1>;

我怎样才能做到这一点?

这是正确的语法:

template <class T, unsigned int n>
using rowVector = Matrix<T, 1, n>;
template <class T, unsigned int m>
using colVector = Matrix<T, m, 1>;

我相信你一定有比你发布的更多的代码,因为这个

template<class T, unsigned int m, unsigned int n>
class Matrix {};
template<class T, unsigned int m, unsigned int n>
using rowVector<T,n> = Matrix<T,1,n>;
template<class T, unsigned int m, unsigned int n>
using colVector<T,m> = Matrix<T,m,1>;

导致以下错误

prog.cc:5:16: error: expected '=' before '<' token
using rowVector<T,n> = Matrix<T,1,n>;
^
prog.cc:5:16: error: expected type-specifier before '<' token
prog.cc:8:16: error: expected '=' before '<' token
using colVector<T,m> = Matrix<T,m,1>;
^
prog.cc:8:16: error: expected type-specifier before '<' token

别名模板的正确语法是:

template < template-parameter-list >
using identifier attr(optional) = type-id ;

所以修复是

template<class T, unsigned int m, unsigned int n>
using rowVector = Matrix<T,1,n>;
template<class T, unsigned int m, unsigned int n>
using colVector = Matrix<T,m,1>;

我想你想去掉m作为rowVector的参数,去掉n作为colVector:的参数

template<class T, unsigned int n>
using rowVector = Matrix<T,1,n>;
template<class T, unsigned int m>
using colVector = Matrix<T,m,1>;