4

what is the difference between the following two snippets?

  1. with <T> for operator <<
template<typename T>
class Stack {
...
friend std::ostream& operator<< <T> (std::ostream&,
Stack<T> const&);
};
  1. without <T>
template<typename T>
class Stack {
...
friend std::ostream& operator<< (std::ostream&,
Stack<T> const&);
};
Willi
  • 317
  • 1
  • 8

1 Answers1

7

In #1, the compiler will look for a function template called operator<< such that operator<< <T> has the precise signature given, and the class Stack<T> will befriend only that particular specialization.

In #2, the compiler will look for a non-template function called operator<< which has the precise signature given. If such a function is found, Stack<T> will befriend it. If such a function is not found, the function is thereby declared (but this is a problematic situation since there's no way to generically define it).

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • In #1, if U is used instead of T in `Stack` i.e, `friend std::ostream& operator<< (std::ostream&, Stack const&);`, is it the same as before this changes? – Willi Aug 30 '21 at 18:49
  • @Willi There needs to be a declaration of `U` in order to make sense of that. Is it another template parameter? Anyway, you should post a new question to ask about that scenario. Comments should only be used to ask for clarification about the answer to the original question. The comments section is not really suitable for writing out more than 1 line of code. – Brian Bi Aug 30 '21 at 19:14
  • you are right. There should be another template parameter. I got it. Thanks! – Willi Aug 30 '21 at 19:27