C++: overloading operator<< for template class

Ask a question+

I define operator<< outside the class template and get an error.

template <class T>
class User
   User(T _age) : age(_age) {}; 

   friend ostream& operator<< (ostream & os, const User<T>& u); 
   T age;

int main()

   int a = 18; 
   User<int> u1(a);

   std::cout << u1 << std::endl;
   return 0;

template <class T>
ostream& operator<<(ostream &os, const User<T>& u)
   os << u.age;
   return os; 

Only after inlining an operator the code compiles.
What are the rules in this regard?

Tigran 1.1K
add comment

0 Answer

Your Answer