模板初始化:

时间:2020-02-22 12:17:50

标签: c++ templates matrix vector alias

我想从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>;

任何指针该如何实现?

2 个答案:

答案 0 :(得分:3)

这是正确的语法:

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

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

答案 1 :(得分: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

alias template的正确语法是:

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>;