friend declaration declares a non-template function(友元声明声明了一个非模板函数)
问题描述
我有一个类似于下面代码的基类.我试图重载 <<与 cout 一起使用.但是,g++ 说:
I have a base Class akin to the code below. I'm attempting to overload << to use with cout. However, g++ is saying:
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
我试过在 << 之后添加 <>在类声明/原型中.但是,然后我得到它不匹配任何模板声明.我一直在尝试将运算符定义完全模板化(我想要),但我只能使用以下代码使其与手动实例化运算符一起工作.
I've tried adding <> after << in the class declaration / prototype. However, then I get it does not match any template declaration. I've been attempting to have the operator definition fully templated (which I want), but I've only been able to get it to work with the following code, with the operator manually instantiated.
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 中包含此或类似内容:
I want to just have this or similar in the 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;
}
我在网上的其他地方读到过将 <> 放在 << 之间.原型中的和 () 应该解决这个问题,但事实并非如此.我可以将其放入单个函数模板中吗?
I've read elsewhere online that putting <> between << and () in the prototype should fix this, but it doesn't. Can I get this into a single function template?
推荐答案
听起来你想改变:
friend ostream& operator << (ostream& out, const Base<T>& e);
致:
template<class T>
friend ostream& operator << (ostream& out, const Base<T>& e);
这篇关于友元声明声明了一个非模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:友元声明声明了一个非模板函数
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
