Home > Backend Development > C++ > body text

How to Properly Overload the Angle Bracket Operator for a Template Class?

Linda Hamilton
Release: 2024-11-01 15:29:02
Original
459 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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
Latest Articles by Author
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!