2016-05-15 7 views
4

Ich habe eine Klassenvorlage und eine Operatorvorlage, die auf ihr privates Feld zugreifen muss. Ich kann eine Vorlage Freund machen:Friend spezifische Vorlage Instanziierung von Operator

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; 
} 

Aber ist es möglich, nur operator==<T> Freund für A<T> zu machen und nicht operator==<int> Freund von A<double> machen?

Antwort

6

Wenn Probleme mit friend auftreten, bringen Sie die Deklaration weiter, bevor die A Klasse definiert ist.

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

Dann können Sie es deutlicher friend. Komplettlösung (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

Ja können Sie. Die Syntax lautet wie folgt:

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

Und setzen Sie Ihre operator== Definition (oder auch nur eine Erklärung) vor der A Klasse.

+2

scheint nicht zu funktionieren http://ideone.com/vnu3QR – RiaD

+0

Dies ist kein Compiler-Fehler. Es gibt Orte, wo diese Syntax gültig ist, aber das ist keiner von ihnen. –

+0

@AlanStokes, nun ja, diese Syntax ist hier vollständig gültig. Warum versuchst du es nicht selbst? Setzen Sie einfach 'operator ==' vor die Klasse. – ixSci