Meatfity Meatfity - 3 months ago 23
C++ Question

Friend functions with templates

I have a generic class , Array1d, with a friend function declared as,

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


and defined as

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;
}


but if I try,

Array1D<int> a;
cout<<a;


I get this error

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


I have tried instatiating it explicitly for 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;
}


But it gives the same error. Help appreciated.

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

These two are not the same functions. This is because Array1D<T> is a concrete type. If you want 1. to match for 2., you need to make it a template, possibly by making it Array1D<U>. You might as well check that T=U, if you want to be over-cautious.

Comments