我的问题与 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/