相关疑难解决方法(0)

重载friend operator <<为模板类

我正在尝试重载运算符<<作为模板类对的朋友,但我不断收到编译器警告说

friend declaration std::ostream& operator<<(ostream& out, Pair<T,U>& v) declares a non template function
Run Code Online (Sandbox Code Playgroud)

对于此代码:

friend ostream& operator<<(ostream&, Pair<T,U>&);
Run Code Online (Sandbox Code Playgroud)

作为推荐说,它给出了第二个警告

if this is not what you intended, make sure the function template has already been declared and add <> after the function name here
Run Code Online (Sandbox Code Playgroud)

这是函数定义

template <class T, class U>
ostream& operator<<(ostream& out, Pair<T,U>& v)
{
    out << v.val1 << " " << v.val2;
}
Run Code Online (Sandbox Code Playgroud)

这是整个班级.

template <class T, class U>
class Pair{
public:
    Pair(T v1, U v2) : val1(v1), val2(v2){} …
Run Code Online (Sandbox Code Playgroud)

c++ operators

28
推荐指数
2
解决办法
3万
查看次数

模板类的模板友好功能

我与中描述的问题挣扎了这个问题(声明一个模板函数作为模板类的朋友),我相信第二个答案就是我想要做的(向前声明模板函数,然后将其命名一个专门为好友).我有一个问题,一个稍微不同的解决方案是否实际上是正确的,或者只是恰好在Visual C++ 2008中工作.

测试代码是:

#include <iostream>

// forward declarations
template <typename T>
class test;

template <typename T>
std::ostream& operator<<(std::ostream &out, const test<T> &t);

template <typename T>
class test {
  friend std::ostream& operator<< <T>(std::ostream &out, const test<T> &t);
  // alternative friend declaration
  // template <typename U>
  // friend std::ostream& operator<<(std::ostream &out, const test<T> &t);

  // rest of class
  };

template <typename T>
std::ostream& operator<<(std::ostream &out, const test<T> &t) {
  // output function defined here
  }
Run Code Online (Sandbox Code Playgroud)

首先,我发现一个奇怪的事情是,如果我更改前向声明operator<<以使其不匹配(例如std::ostream& …

c++ templates visual-c++ friend-function

9
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×2

friend-function ×1

operators ×1

templates ×1

visual-c++ ×1