2

我的问题与这个有点相关。

我想为某些类重载运算符 << ,我发现两种不同的符号都可以工作:

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的朋友时更具限制性?

4

2 回答 2

1

第一个版本将友谊限制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;
}
于 2010-01-16T09:48:07.407 回答
0

碰巧友元函数的定义对模板有一个例外。它允许你这样写:

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>您创建的每个实例自动创建的普通函数。

供参考: http: //www.parashift.com/c++-faq-lite/templates.html#faq-35.16

于 2010-01-16T10:39:22.233 回答