My question ist related a bit to this one.
I want to overload the operator << for some class and I found two different notations that both work:
template <class T>
class A{
T t;
public:
A(T init) : t(init){}
friend ostream& operator<< <> (ostream &os, const A<T> &a); //need forward declaration
//template <class U> friend ostream& operator<< (ostream &os, const A<U> &a);
};
Do I define identical things with different notations? Or is the first version more restrictive in which instance (in this case only the instance with the same T as my class A) of << is friend of A?
It so happens that the definition of friend functions have an exception for templates. It allows you to write this:
And it has the advantage of creating a normal function automatically created for each instance of
A<T>
you create.For reference: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16
The first version restricts the friendship to the
operator<<
for the specific typeA<T>
, while the second makes anyoperator<<
that takes anA<SomeType>
a friend.So yes, the first one is more restrictive: