I\'m trying to implement a linked list. But I\'m receiving an error when I try overloading the << operator. This is my program:
#include
#i
Since they take a class template argument, your friends
need to be function templates, or specializations of function templates:
// function template friend
template <typename T2>
friend ostream& operator<<(ostream& out, const List<T2>& li);
Note that one would usually overload this operator to take a reference, not a pointer, as in the example above.
The drawback is that this is probably not restrictive enough: ostream& operator<<(ostream& out, const List<Widget>& li)
would be a friend of List<int>
. Since this is not usually the desired behaviour, you can provide a template specialization, which would restrict friendship to the same T
as that with which the class is instantiated:
// function template, declared outside of the class:
template <typename T>
ostream& operator<<(ostream& out, const List<T2>& li);
// function template specialization, declared inside the class:
friend ostream& operator<< <>(ostream& out, const List<T>& li);