我有一个类似于下面代码的基类。我正在尝试重载 << 以与 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
我尝试在类声明/原型(prototype)中的 << 之后添加 <>。但是,然后我得到它 不匹配任何模板声明
。我一直在尝试将运算符定义完全模板化(我想要),但我只能让它与以下代码一起使用,并手动实例化运算符。
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;
}
我只想在 header 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;
}
我在网上其他地方读到,在原型(prototype)中将 <> 放在 << 和 () 之间应该可以解决这个问题,但事实并非如此。我可以把它放到一个函数模板中吗?
最佳答案
听起来你想改变:
friend ostream& operator << (ostream& out, const Base<T>& e);
收件人:
template<class T>
friend ostream& operator << (ostream& out, const Base<T>& e);
关于c++ - friend 声明声明了一个非模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4039817/