其他分享
首页 > 其他分享> > c – friend声明声明一个非模板函数

c – friend声明声明一个非模板函数

作者:互联网

参见英文答案 > overloading friend operator<< for template class                                    5个
我有一个基类类似于下面的代码.我试图重载<<与cout一起使用.
然而,g说:

base.h:24: warning: friend declaration ‘std::ostream& operator<<(std::ostream&, Base<T>*)’ declares a non-template function
base.h:24: warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning

我试过添加<>在<<在类声明/原型中.但是,我得到它与任何模板声明都不匹配.我一直试图让操作符定义完全模板化(我想要),但我只能使用以下代码使用操作符手动实例化. base.h

template <typename T>
class Base {
  public:
    friend ostream& operator << (ostream &out, Base<T> *e);
};

base.cpp

ostream& operator<< (ostream &out, Base<int> *e) {
    out << e->data;
return out;
}

我想在标题base.h中有这个或类似的东西:

template <typename T>
class Base {
  public:
    friend ostream& operator << (ostream &out, Base<T> *e);
};

template <typename T>
ostream& operator<< (ostream &out, Base<T> *e) {
    out << e->data;
return out;
}

我在网上其他地方读到过<>之间<<原型中的()应该解决这个问题,但事实并非如此.我可以把它变成一个单一的功能模板吗?

解决方法:

听起来你想要改变:

friend ostream& operator << (ostream& out, const Base<T>& e);

至:

template<class T>
friend ostream& operator << (ostream& out, const Base<T>& e);

标签:specialization,c,templates,operator-overloading,friend
来源: https://codeday.me/bug/20190925/1817675.html