为什么在编译模板化类时遇到麻烦?

时间:2019-05-09 21:54:47

标签: c++ templates

我在这段代码上停留了一段时间,无法编译它,我到底在做什么错?如果在编译时存在错误,请忽略它们,因为我可以自己解决此问题。截至目前,我只是试图使其运行。预先谢谢你。

#include <iostream>
#include <string.h>

//template <class t> class Matrix; //possible way of fixing the friend function.

using namespace std;
  template<class T, size_t NROWS, size_t NCOLS>
  std::ostream & operator<<(std::ostream &os, const Matrix<T,NROWS, NCOLS> &matrix);


template<class T, size_t NROWS = 1, size_t NCOLS = 1>
class Matrix{
public:
  Matrix(){}
  friend std::ostream &operator<< <>(std::ostream&os,const Matrix<T, NROWS, NCOLS> &matrix);

private:
  T container[NROWS][NCOLS];
};


template<class T,size_t NROWS, size_t NCOLS>
  std::ostream &operator<<(std::ostream &os,const Matrix<T,NROWS,NCOLS>&matrix){
  for(size_t i=0;i<NROWS;++i){
    for(size_t j=0;j<NCOLS;++j){
      os  <<matrix.container[i][j]<<" ";
    }
    os <<std::endl;
  }
  os <<std::endl;
}


int main(){
  Matrix<float, 10, 5> mat;
  cout << mat;
  return 0;
}

我使用的IDE中的错误如下:

  

main.cpp:8:51:错误:没有名为“矩阵”的模板   std :: ostream&运算符<<(std :: ostream&os,const Matrix&matrix);

     

main.cpp:15:24:错误:没有功能模板与功能模板专业化匹配'operator <<'朋友std :: ostream&operator << <>(std :: ostream&os,const Matrix&matrix);

     

main.cpp:35:32:注意:在实例化模板类“ Matrix”时,此处要求矩阵垫;

3 个答案:

答案 0 :(得分:3)

如果取消注释第4行,并进行如下更改,则您拥有的代码将编译:

template <class t, size_t, size_t> class Matrix; //possible way of fixing the friend function.

似乎您的问题是,前向声明的Matrix模板参数与后来出现的Matrix定义不匹配。

此外,尽管代码将在此修复后进行编译,但仍然可能有您要修复的警告:

In function 'std::ostream& operator<<(std::ostream&, const Matrix<T, NROWS, NCOLS>&)':
31:1: warning: no return statement in function returning non-void [-Wreturn-type]

答案 1 :(得分:1)

D:\BACKUPS\new_file_090519.txt

请删除C标头#include <cstddef> #include <iostream> template<typename, std::size_t, std::size_t> class Matrix; template<typename T, std::size_t NROWS, std::size_t NCOLS> std::ostream& operator<<(std::ostream &os, Matrix<T, NROWS, NCOLS> const &matrix) { for (std::size_t row{}; row < NROWS; ++row, os.put('\n')) for (std::size_t col{}; col < NCOLS; ++col) os << matrix.container[row][col] << ' '; return os.put('\n'); } template<typename T, std::size_t NROWS = 1, std::size_t NCOLS = 1> class Matrix { T container[NROWS][NCOLS] = {}; friend std::ostream& operator<< <>(std::ostream&, Matrix<T, NROWS, NCOLS> const&); }; int main() { Matrix<float, 10, 5> mat; std::cout << mat; }

答案 2 :(得分:1)

您需要在使用矩阵之前对其进行定义:

template<class T, size_t NROWS = 1, size_t NCOLS = 1>
class Matrix;

并将返回语句添加到运算符<<,返回os。您也不需要重复operator <<声明,您只能在类主体中声明它。