c++ - friend 声明声明了一个非模板函数

标签 c++ templates operator-overloading friend specialization

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

相关文章:

c++ - 更改派生类中打包结构的位大小

c++ - 如果只创建一次,使用数百个线程是否安全?

java - 哪些模板语言可同时用于 Java 和 Javascript?

c++ - 从 std::ostream 重载 << 运算符时,为什么编译器会给出 "too many parameters for this operator function"错误?

c++ - 使用 std::pairs 数组初始化 std::map 问题(指针错误?)

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 在依赖于类型的上下文中使用 constexpr

C++ 模板函数自动静态? (不,他们不是)

c++ - 在模板类中找不到错误

c++ - 传递 operator== 以在 C++ 中设置