2

私の質問はこれに少し関連しています。

一部のクラスの演算子 << をオーバーロードしたいのですが、両方が機能する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>ますが、2 番目のバージョンはフレンド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 に答える