有关模板的友元函数记录
- 错误信息如下
matrix.h:10:56: warning: friend declaration ‘std::ostream& operator<<(std::ostream&, const matrix<T>&)’ declares a non-template function [-Wnon-template-friend]
friend ostream& operator<< (ostream&, const matrix<T>&);
在优快云上找到 这篇博客,然后根据这篇博客进行修改 https://blog.youkuaiyun.com/qq_37341466/article/details/81626193
- 首先按照“模板类的约束模板友元”类型更改,原来的写法是“非模板友元”
friend ostream& operator<< <>(ostream&, const matrix<T>&);
之后出现 如下错误
matrix.h:10:18: error: template-id ‘operator<< <>’ for ‘std::ostream& operator<<(std::ostream&, const matrix<int>&)’ does not match any template declaration
friend ostream& operator<< <>(ostream&, const matrix<T>&);
这个错误是因为我之前没有申明这个友元函数,所以不能或爆出这个错误。
之后在类声明之前加入如下语句
template <class T>
class matrix;
template <class T>
ostream& operator<<(ostream&, const matrix<T>&);
之前的错误就直接消失了
总结
- 在调用模板的类的友元函数时,需要在函数名后面加一个
< >
将友元函数变成__模板类的约束模板友元__ - 使用友元函数的时候需要在类外部进行声明,不然会出现__错误2__
- 参考博客中的第三类友元函数:模板类的非约束模板友元,在类的内部声明友元,每个模板函数(类)具体化都是每个类具体化的友元,对于非约束友元,友元模板类型参数与模板类型 参数是不同的