Overloading << operator in C++ when using templates in linked list program

后端 未结 1 1333
面向向阳花
面向向阳花 2021-01-27 02:47

I\'m trying to implement a linked list. But I\'m receiving an error when I try overloading the << operator. This is my program:

#include
#i         


        
相关标签:
1条回答
  • 2021-01-27 03:28

    Since they take a class template argument, your friends need to be function templates, or specializations of function templates:

    // function template friend
    template <typename T2>
    friend ostream& operator<<(ostream& out, const List<T2>& li);
    

    Note that one would usually overload this operator to take a reference, not a pointer, as in the example above.

    The drawback is that this is probably not restrictive enough: ostream& operator<<(ostream& out, const List<Widget>& li) would be a friend of List<int>. Since this is not usually the desired behaviour, you can provide a template specialization, which would restrict friendship to the same T as that with which the class is instantiated:

    // function template, declared outside of the class:
    template <typename T>
    ostream& operator<<(ostream& out, const List<T2>& li);
    
    // function template specialization, declared inside the class:
    friend ostream& operator<< <>(ostream& out, const List<T>& li);
    
    0 讨论(0)
提交回复
热议问题