Search code examples
c++class-template

Type parameter <T> behind the “function name” operator


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&);
};

Solution

  • 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).