【问题标题】:Friend functions with templates带模板的朋友功能
【发布时间】:2016-08-27 13:48:30
【问题描述】:

我有一个泛型类 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;
}

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

【问题讨论】:

  • 一个用于重现错误的最小工作示例也将不胜感激。

标签: c++ templates operator-overloading friend


【解决方案1】:
  1. friend std::ostream&amp; operator&lt;&lt; &lt;&gt;(std ::ostream&amp; out, Array1D&lt;T&gt;&amp; a);
  2. template<typename U> std::ostream& operator<< (std ::ostream& out, Array1D<U> a)

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

【讨论】:

  • 有没有办法做到这一点,而无需在类中定义函数?
  • 是的,模板还是在类外定义的。
猜你喜欢
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
  • 2010-10-29
  • 1970-01-01
  • 2019-06-27
  • 2015-09-29
相关资源
最近更新 更多