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.
source share