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

后端 未结 1 1332
面向向阳花
面向向阳花 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 
    friend ostream& operator<<(ostream& out, const List& 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& li) would be a friend of List. 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 
    ostream& operator<<(ostream& out, const List& li);
    
    // function template specialization, declared inside the class:
    friend ostream& operator<< <>(ostream& out, const List& li);
    

    0 讨论(0)
提交回复
热议问题