朋友声明声明了非模板函数 [英] friend declaration declares a non-template function

查看:207
本文介绍了朋友声明声明了非模板函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于以下代码的基类.我正在尝试超载<<与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

我曾尝试在<<<之后添加<>.在类声明/原型中.但是,然后得到它does not match any template declaration.我一直在尝试对操作符定义进行完全模板化(我想要),但是我只能通过手动实例化操作符来使它与以下代码一起使用.

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);

这篇关于朋友声明声明了非模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆