Reputation: 11
I don't know what is wrong when trying to overload >> and <<
template<class T, int N> class vector{
friend istream &operator>> <T,N>(istream &, vector &);
friend ostream &operator<< <T,N>(ostream &, const vector &);
};
template<class T, int N>
istream &operator>>(istream &input, vector<T,N>& v)
{
for (int i=0; i<N; i++)
input >> v.component[i];
return input;
}
The g++ compiler says
vector.h:22:17: error: template-id ‘operator>><double, 2>’ for
‘std::istream& operator>>(std::istream&, vector<double, 2>&)’
does not match any template declaration
friend istream &operator>> <T,N>(istream &, vector &);
^
vector.h:23:17: error: template-id ‘operator<< <double, 2>’ for
‘std::ostream& operator<<(std::ostream&, const vector<double, 2>&)’
does not match any template declaration
friend ostream &operator<< <T,N>(ostream &, const vector &);
^
Upvotes: 1
Views: 1739
Reputation: 96845
The way you've written the overload is indicative of a function template specialization. Hence the error since there was no previously-declared primary template. If this is the primary definition (which it is) you only need the template arguments from the enclosing class declaration because they are impiled when you use the class name as an argument:
template<class T, int N> class vector {
friend istream &operator>> (istream &, vector &);
friend ostream &operator<< (ostream &, const vector &);
};
That is only special for the in-class declaration of the function. You could also accept template arguments of different types and values:
template<class T, int N> class vector {
template<class T2, int N2>
friend istream &operator>> (istream &, vector<T2, N2> &);
template<class T2, int N2>
friend ostream &operator<< (ostream &, const vector<T2, N2> &);
};
Upvotes: 0
Reputation: 52324
You need a declaration of the template before the point it is made friend (i.e. the friend clause can't declare the template like it does for functions).
template<class T, int N> class vector;
template<class T, int N>
istream &operator>>(istream &input, vector<T,N>& v);
template<class T, int N>
ostream &operator<<(ostream &input, vector<T,N> const& v);
template<class T, int N> class vector{
friend istream &operator>> <T,N>(istream &, vector &);
friend ostream &operator<< <T,N>(ostream &, const vector &);
};
template<class T, int N>
istream &operator>>(istream &input, vector<T,N>& v)
{
for (int i=0; i<N; i++)
input >> v.component[i];
return input;
}
Upvotes: 1