朋友功能与模板

时间:2016-08-27 13:48:30

标签: c++ templates operator-overloading friend

我有一个泛型类Array1d,其友元函数声明为

std::map<connection_hdl,connection_data,std::owner_less<conn‌​ection_hdl>> con_list; con_list m_connections;

并定义为

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;

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

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

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

1 个答案:

答案 0 :(得分:1)

  1. template<typename U> std::ostream& operator<< (std ::ostream& out, Array1D<U> a)
  2. Array1D<T>
  3. 这两个功能不同。这是因为Array1D<U>是具体类型。如果您希望1.匹配2.,您需要将其设为模板,可能需​​要将其设为itemList。如果你想过于谨慎,你也可以检查T = U.