首页 > 解决方案 > 为什么我在编译模板类时遇到问题?

问题描述

我已经在这段代码上停留了一段时间,无法编译,我到底做错了什么?如果编译时出现错误,请忽略它们,因为我可以自己修复。截至目前,我只是想让它运行。先感谢您。

#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: 错误:没有名为 'Matrix' 的模板 std::ostream & operator<<(std::ostream &os, const Matrix &matrix);

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

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

标签: c++templates

解决方案


如果您取消注释第 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]

推荐阅读