This friend function declaration within the class template definition
friend void operator << (vector &v, T data);
is not a template function (though it is a templated entity if it is defined within the class).
On the other hand, this declaration outside the class template definition
template<class T>
void operator << (vector<T> &v, T data){
cout << data;
}
defines a template function.
Either define the friend function in the class definition. And in this case the compiler will generate the definition of the function for each used specialization of the class template. Or for each used class specialization you have to define (provide) a separate non-template friend function explicitly yourself.
Here is a demonstrative program
#include<iostream>
template<class T>
class vector{
int d;
public:
vector(){
d = 0;
}
vector(T data){
d = data;
}
friend void operator << (vector &v, T data);
/*{
cout << data << endl;
}*/
};
template<class T>
void operator << (vector<T> &v, T data)
{
std::cout << data;
}
void operator << (vector<int> &v, int data)
{
std::cout << data;
}
int main()
{
vector<int> v1;
v1 << 10;
return 0;
}
The program output is
10
In the program there are two overloaded functions operator <<
. The first one is a friend non-template function declared in the class definition and the second one is a template function that is not a friend function of the class. For the class specialization vector<int>
used in main you have to provide the non-template friend function definition outside the class.
Or you could define the friend function within the class.