Templates and friends

When reading from Thinking in C ++ Volume 2 from the chapter "Templates in depth", I see that if you have a friendly function in the template class, you need to forward the declaration of this function. I did this example to verify this by overriding the output statement:

#include <iostream> using namespace std; /* template<class T> class X; template<class T> ostream& operator << (ostream& os, const X<T>& x); */ template<class T> class X { T t; public: X(T i): t(i) {} friend ostream& operator << (ostream& os, const X<T>& x) { return os << xt; } }; int main() { X<int> a(1); cout << a; return 0; } 

But it works without a direct declaration, but then I test it with the definition of <<outside the class:

 friend ostream& operator << <>(ostream& os, const X<T>& x); (inside of the class) template<class T> ostream& operator << (ostream& os, const X<T>& x) { return os << xt; } 

I am not sure why with the definition inside the class that it does not apply, is it because you have to indicate that the ostream operation function is a template? (using <>)

Sorry for the confusion.

+4
source share
1 answer

Since it seems that my comment was satisfactory, here it is in the form of an answer.

The C ++ FAQ Lite has a chapter on this , which, for completeness, boils down to two possible ways to convince the compiler while it examines the body of class X that the function of the friend operator<< actually a function template.

One approach, like you, declared the operator<< function template before the class definition and used <> in a friend line inside the class body, providing the wonderful syntax operator << <>( .

Another approach is to define the whole body of a friendโ€™s template function inside the body of class X, making forward declaration unnecessary.

+2
source

All Articles