我有一个类似下面代码的基类。我尝试重载 << 以便在 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;
}
我在其他网站上看到说在原型中在 << 和 () 之间添加 <> 可以解决这个问题,但实际上并没有。是否可以将其放入单个函数模板中?