Home > Article > Backend Development > How to Properly Overload the Angle Bracket Operator for a Template Class?
Overloading the Angle Bracket Operator for a Template Class
Trying to overload the << operator as a friend to a template class Pair, one may encounter a compiler warning indicating a non-template function declaration. This issue arises due to a discrepancy between the friend declaration and the actual function definition.
To resolve this, one must specify that the friend declaration applies to a specialized instance of the template class Pair with specific template arguments. This is achieved by using empty angle brackets <> after the operator declaration in the friend declaration.
The corrected code looks like this:
<code class="cpp">template <class T, class U> class Pair { public: Pair(T v1, U v2) : val1(v1), val2(v2) {} ~Pair() {} Pair& operator=(const Pair&); friend ostream& operator<<<> (ostream&, Pair<T, U>&); private: T val1; U val2; };</code>
Additionally, the function definition for the overloaded operator must be declared before the template class definition, as follows:
<code class="cpp">template <class T, class U> ostream& operator<<<> (ostream& out, Pair<T, U>& v); template <class T, class U> class Pair { // ... };</code>
By making these changes, the compiler can correctly identify the friend function as a specialization for the Pair template and avoid the warning regarding a non-template function declaration.
The above is the detailed content of How to Properly Overload the Angle Bracket Operator for a Template Class?. For more information, please follow other related articles on the PHP Chinese website!