朋友函数在模板定义 [英] friend function in template definition
问题描述
我的问题ist与这个有关。
我想重载运算符<<对于一些类,我发现两个不同的符号都工作:
template< class T&
class A {
T t;
public:
A(T init):t(init){}
friend ostream&运算符<< <> (ostream& os,const A< T& a); //需要前进声明
// template< class U>朋友ostream&运算符<< (ostream& os,const A U& a);
}
我用不同的符号定义相同的东西吗?或者是第一版本在其中实例(在这种情况下只有具有与我的类A相同的T的实例)更限制的<<
第一个版本将友谊限制在运算符 c> code>用于特定类型
A< T>
,而第二种使任何
因此,是的,第一个更具限制性:
template< class T>
ostream&运算符<< (ostream& os,const A< T& a){
A double> b(0.0);
b.t; //编译错误版本1,精细版本2
return os;
}
int main(){
A< int> a(0);
cout<< a<< endl;
}
My question ist related a bit to this one.
I want to overload the operator << for some class and I found two different notations that both work:
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);
};
Do I define identical things with different notations? Or is the first version more restrictive in which instance (in this case only the instance with the same T as my class A) of << is friend of A?
The first version restricts the friendship to the operator<<
for the specific type A<T>
, while the second makes any operator<<
that takes an A<SomeType>
a friend.
So yes, the first one is more restrictive:
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;
}
这篇关于朋友函数在模板定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!