2016-05-15 3 views
4

プライベートフィールドにアクセスする必要があるクラステンプレートとオペレータテンプレートがあります。私は、テンプレートの友人作ることができます。オペレータのフレンド固有のテンプレートのインスタンス

template <typename T> 
class A { 
    int x; 
    template <typename U> 
    friend bool operator==(const A<U>& a, const A<U>& b); 
}; 

template <typename T> 
bool operator== (const A<T>& a, const A<T>& b) { 
    return a.x == b.x; 
} 

int main() { 
    A<int> x, y; 
    x == y; 
    return 0; 
} 

をしかし、それはA<T>のみoperator==<T>友人を作り、A<double>operator==<int>友人をしていないすることは可能でしょうか?

答えて

6

friendに問題がある場合は、Aクラスが定義される前に宣言を前方に持ってください。

template <typename T> 
bool operator== (const A<T>& a, const A<T>& b); 

次に、friendより明確に指定できます。完全なソリューション(ideone):

template <typename T> 
class A; 

// declare operator== early (requires that A be introduced above) 
template <typename T> 
bool operator== (const A<T>& a, const A<T>& b); 

// define A 
template <typename T> 
class A { 
    int x; 
    // friend the <T> instantiation 
    friend bool operator==<T>(const A<T>& a, const A<T>& b); 
}; 

// define operator== 
template <typename T> 
bool operator== (const A<T>& a, const A<T>& b) { 
    return a.x == b.x; 
} 
2

はいできます。構文は次のとおりです。

template <typename T> 
class A { 
    int x; 
    friend bool operator==<>(const A& a, const A& b); 
}; 

そしてAクラスの前に、あなたのoperator==定義(または単に宣言)を置きます。

+2

http://ideone.com/vnu3QRを動作していないよう – RiaD

+0

これはコンパイラのバグではありません。その構文が有効な場所がありますが、これはその1つではありません。 –

+0

@AlanStokesですが、この構文は完全に有効です。どうしてあなた自身を試してみませんか?クラスの前に 'operator =='を入れてください。 – ixSci

関連する問題