【问题标题】:Template initialization:模板初始化:
【发布时间】:2020-02-22 12:17:50
【问题描述】:

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

任何指针我该如何做到这一点?

【问题讨论】:

  • 请在问题中逐字包含错误

标签: c++ templates matrix vector alias


【解决方案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>;

【讨论】:

  • 谢谢。 :) 你有什么好的资源可以让我学习模板和一些特殊主题,例如模板中的运算符重载以及与继承的结合。
  • @Prajwal_7 C++ Primer 5th edition 是一本很棒的书,其中有关于您提到的主题的章节。我向所有正在学习 C++ 的人强烈推荐这本书。
【解决方案2】:

我相信你的代码肯定比你发布的要多,因为这个

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

【讨论】:

  • 谢谢。也许我把我的问题放错了。我已经定义了一个矩阵类。 Matrix,现在我想使用两种特殊情况,即行向量和列向量。在主要功能中,我想初始化。例如: rowVector 应该等同于 : Matrix 自动。我想实现这个.. 我该怎么做?
  • @Prajwal_7 看到我的回答。 rowVector&lt;int, 2&gt; 等价于Matrix&lt;int, 1, 2&gt;colVector&lt;int, 2&gt; 等价于Matrix&lt;int, 2, 1&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
  • 1970-01-01
  • 2022-01-05
  • 2012-08-29
  • 1970-01-01
相关资源
最近更新 更多