C++: overloading operator<< for template class

Ask a question
0

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

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

   friend ostream& operator<< (ostream & os, const User<T>& u); 
private:
   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 rules in this regard?

Coin iconoffer bounty
add comment

0 Answer

Your Answer