2012-07-30 9 views
5

(のstd :: ostreamに&オペレータ< <)テンプレートクラスのフレンド関数を宣言するための正しい方法は何ですか.cppファイルで?C++:オペレータのためのテンプレートクラスのフレンド関数<<

私の現在の実装では動作しません:

// MyTest.h 
template<class T, unsigned int TSIZE> class MyTest 
{ 
    inline friend std::ostream& operator<< <T, TSIZE> (std::ostream &lhs, const MyTest<T, TSIZE> &rhs); 
}; 

// MyTest.cpp 
template<class T, unsigned int TSIZE> inline friend std::ostream& operator<< <T, TSIZE> (std::ostream &lhs, const MyTest<T, TSIZE> &rhs) 
{ 
    // IMPLEMENTATION 
} 

はどうもありがとうございました!

+0

"動作しません"という正確な意味...コンパイラエラー?どのエラー?最初の推測... "友人"は.cppバージョンに属していません。 –

答えて

7

テンプレートの専門用語であるoperator<< <T, TSIZE>のように、プライマリテンプレートの宣言を表示する必要があります。次にoperator<<は、パラメータとして表示されるため、MyTestの宣言が必要です。

// Declare MyTest because operator<< needs it 
template<class T, unsigned int TSIZE> class MyTest; 

// Declare primary template 
template<class T, unsigned int TSIZE> 
inline std::ostream& operator<<(std::ostream& lhs, const MyText<T, TSIZE>& rhs); 

template<class T, unsigned int TSIZE> class MyTest 
{ 
    // Specialization MyTest<T, TSIZE> only declares 
    // specialization operator<< <T, TSIZE> as friend 
    // Note that you can just use '<>' to designate the specialization, 
    // template parameters are deduced from the argument list in this case 
    inline friend std::ostream& operator<< <> (std::ostream &lhs, const MyTest<T, TSIZE> &rhs); 
}; 

これらの宣言と一致する必要があります。 operator<<はテンプレートなので、その定義はヘッダ内にあるはずです。

これらのプリエンプティブな宣言をすべて記述するときに必要な作業が少なくて済むのは、MyTest<T, TSIZE>の特殊化だけでなく、テンプレート全体をフレンドとして宣言することです。

// in MyTest definition 
template<typename U, unsigned USIZE> 
inline friend std::ostream& operator<<(std::ostream& lhs, const MyTest<U, USIZE>& rhs); 

あなたが持っている定義はまた、このような宣言一致する必要があります(テンプレートパラメータの名前が一致する宣言と定義とは関係ありません)。

完全性のために、私は、クラステンプレートの友人になると、それをクラステンプレート定義で定義することを言及します。これは、各専門分野に固有の非テンプレート友人機能を定義します。

// in MyTest definition 
friend std::ostream& operator<<(std::ostream& lhs, MyTest const& rhs) 
{ /* implementation */ } 

そのような関数を参照することは不可能である(例えば&ns::operator<<が他のオプションとは異なり、動作しない)、これらは唯一ADLを介して発見されます。

0

元の投稿が望んだ内容が完全にはっきりしていません。

// Some template class. 
template<class T, unsigned int TSIZE> class MyTest { }; 

// Some template function. 
template<class T, unsigned int TSIZE> std::ostream& operator<< (std::ostream &lhs, const MyTest<T, TSIZE> &rhs) 
{ 
    // IMPLEMENTATION 
} 

今ではこの機能はMy testの保護されたオブジェクトにアクセスする必要があるため、クラスの友人として、このテンプレート関数を宣言する必要がある:私はそれは、次の望んでいたと仮定します。これは、次の定義を用いて達成することができます。これは、現在のテンプレートクラスに属していない無関係なテンプレート関数であるため

template<class T, unsigned int TSIZE> class MyTest 
{ 
    template<class T1, unsigned int TSIZE1> 
    friend std::ostream& operator<< (std::ostream &lhs, const MyTest<T1, TSIZE1> &rhs); 
}; 

テンプレートのヘッダーはfriend宣言の前に必要とされています。

関連する問題