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

£可爱£侵袭症+ 提交于 2019-12-02 06:17:45

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!