c++ - 模板定义中的友元函数

标签 c++ templates friend-function

我的问题与 this 有点相关一个。

我想为某些类重载运算符 <<,我发现两种不同的符号都有效:

template <class T>
class A{
  T t;
public:
  A(T init) : t(init){}
  friend ostream& operator<< <> (ostream &os, const A<T> &a); //need forward declaration
  //template <class U> friend ostream& operator<< (ostream &os, const A<U> &a);
};

我是否用不同的符号来定义相同的事物?或者第一个版本在 << 的哪个实例(在本例中只有与我的类 A 具有相同 T 的实例)是 A 的 friend 时更具限制性?

最佳答案

第一个版本将友元限制为operator<<对于特定类型 A<T> , 而第二个使任何 operator<<这需要 A<SomeType>一个 friend 。

所以是的,第一个限制性更强:

template<class T>
ostream& operator<< (ostream& os, const A<T>& a) {
    A<double> b(0.0);
    b.t; // compile error with version 1, fine with version 2
    return os;
}

int main() {
    A<int> a(0);
    cout << a << endl;
}

关于c++ - 模板定义中的友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2076874/

相关文章:

C++函数问题

c++ - 从实际参数捕获函数参数类型

c++ - 在模板类外部定义非模板函数

sql - Node.js - sqlstring 替代方案,允许命名替换

c++ - 模板类错误 "Expected initializer before ' <' token"

c++ - 在重载 I/O 运算符中重载增量运算符时出错

c++ - 调用类友元函数的类成员函数(都是同一个类)可能吗?

c++ - 当焦点转移到按钮被中断时,QPushButton 卡住绘图按下

C++ Opencl 包装器引用计数?

c++ - 将当前模板用作模板参数之一的模板参数