<<Operator Question in c++ class template.

Asked 2 years ago, Updated 2 years ago, 28 views

There's an error like that in the code above, but I don't know why <

c++

2022-09-22 19:26

1 Answers

If you declare a function within the class with friend as shown below, set the function to friend and declare that the function exists.

template<typename T>
class M {
    // ...
    friend ostream& operator<<(ostream& os, const M<T>& ref);
};

That is, it declares that a generic free function (non-member function) exists called ostream& operator<<(ostream&os, const M<T>&ref).

Afterwards, when calling operator<<() as shown below, you will find a function to call based on the C++ name Name lookup rule.

int main() {
    M<int> m(1);
    std::cout << m;
}

The problem arises here.

If you have a free function and a function template with the same name according to the name lookup rule, you will use the free function without instantiating the function template.

As I mentioned earlier, the free function ostream&operator<<(ostream&os, const M<T>&ref) is declared due to friendostream&operator<<<(ostream&os, const M>>&.

Therefore, main() has a function template template<typename T>ostream&operator<<(ostream&os, const M<T>ref) and only this free function is defined.

The workaround is to clarify that the function is a function template or define a free function when declaring a friend operator.

To specify a function template

template<typename T>
class M {
    // ...
    template<typename U>
    friend ostream& operator<<(ostream& os, const M<U>& ref);
};

Free function definition method

template<typename T>
class M {
    // ...
    friend ostream& operator<<(ostream& os, const M<T>& ref) {
        return os << ref.num;
    }
};

Also, I think it would be easy to answer if you put the code in text, not picture.


2022-09-22 19:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.