Home > Backend Development > C++ > body text

How to Overload Friend Operator `

DDD
Release: 2024-11-01 02:59:27
Original
520 people have browsed it

How to Overload Friend Operator `

Overloading Friend Operator << for Template Class

When trying to overload the << operator as a friend to a template class, you may encounter a compiler warning indicating that it is declaring a non-template function. To resolve this issue, it is necessary to correctly declare the template function before the friend declaration.

In the provided code, the friend declaration for the << operator is:

<code class="cpp">friend ostream&amp; operator<<(ostream&amp;, Pair<T,U>&amp;);<p>However, the compiler recommends adding <> brackets to the function name, indicating that it should be declared as a template function. The correct syntax is:</p>
<pre class="brush:php;toolbar:false"><code class="cpp">friend ostream&amp; operator<< <> (ostream&amp;, Pair<T,U>&amp;);</code>
Copy after login

This declares the << operator as a friend of the template class Pair and specifies that it is a template function with generic parameters T and U.

Remember, the template function declaration should also be placed before the Pair class template definition to ensure that the compiler is aware of the template function when parsing the friend declaration. The corrected code with the correct friend declaration and template function declaration:

template  class Pair;

template 
ostream& operator<< <> (ostream&, Pair&);

// Pair template class definition...

The above is the detailed content of How to Overload Friend Operator `. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!