我的问题与this 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);
};我是否用不同的符号定义了相同的东西?或者第一个版本的限制更多,<<的实例(在本例中只有与我的类A具有相同T的实例)是A的朋友?
发布于 2010-01-16 17:48:07
第一个版本将友谊限制为特定类型A<T>的operator<<,而第二个版本使任何接受A<SomeType>的operator<<都成为朋友。
所以,是的,第一个限制更多:
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;
}发布于 2010-01-16 18:39:22
碰巧友元函数的定义对于模板有一个例外。它允许您编写以下代码:
template <class T>
class A{
T t;
public:
A(T init) : t(init){}
friend ostream& operator<<(ostream &os, const A &a)
{ // Implementation in the class
}
};它的优点是可以为您创建的每个A<T>实例创建一个自动创建的normal函数。
参考:http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16
https://stackoverflow.com/questions/2076874
复制相似问题