我的问题有点相关this https://stackoverflow.com/questions/1297609/overloading-friend-operator-for-template-class/ one.
我想重载某些类的运算符
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);
};
我是否用不同的符号定义相同的事物?或者第一个版本是否更具限制性,其中
第一个版本将友谊限制为operator<<
对于特定类型A<T>
,而第二个使任何operator<<
这需要一个A<SomeType>
一个朋友。
所以是的,第一个更具限制性:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)