带模板的友元函数

Friend functions with templates

我有一个通用的 class Array1d,其友元函数声明为,

friend std::ostream& operator<< <>(std ::ostream& out, Array1D<T>& a);

并定义为

template<typename U>
std::ostream& operator<< (std ::ostream& out, Array1D<U> a){
    for(int i=0;i<a.size;i++){
        out<<a[i]<<" ";
    }
    out<<endl;
    return out;
}

但如果我尝试,

Array1D<int> a;
cout<<a;

我收到这个错误

(1).cpp|62|error: template-id 'operator<< <>' for 'std::ostream& operator<<(std::ostream&, Array1D<int>&)' does not match any template declaration|

我已经尝试为 int 显式实例化它,

std::ostream& operator<< (std ::ostream& out, Array1D<int> a){
    for(int i=0;i<a.size;i++){
        out<<a[i]<<" ";
    }
    out<<endl;
    return out;
}

但它给出了同样的错误。帮助表示赞赏。

  1. friend std::ostream& operator<< <>(std ::ostream& out, Array1D<T>& a);
  2. template<typename U> std::ostream& operator<< (std ::ostream& out, Array1D<U> a)

这两个不是同一个函数。这是因为 Array1D<T> 是具体类型。如果您希望 1. 匹配 2.,则需要将其设为模板,可能是 Array1D<U>。如果你想过于谨慎,不妨检查一下 T=U。