operator== als Template
-
Hi, wie bekommt man am elegantesten das da kompiliert?
#include <iostream> class A { }; class D : public A { }; template <typename T> class B { }; bool operator==(A const & lhs, A const & rhs) { return true; } template <typename T, typename U> bool operator==(T * lhs, B<U> const & rhs) { return false; } template <typename T, typename U> bool operator==(B<T> const & lhs, U * rhs) { return false; } int main() { B<A> b; D * d; std::cout << (b == 0) << std::endl; std::cout << (b == d) << std::endl; std::cout << (0 == b) << std::endl; std::cout << (d == b) << std::endl; }
-
Gegenfrage: Was hast du mit diesem Code vor? Und wo streikt dein Compiler?
-
CStoll schrieb:
Gegenfrage: Was hast du mit diesem Code vor? Und wo streikt dein Compiler?
B ist ein Wrapper um Handler herum. Handler sind Zeigern. Nun möchte ich die Wrapper mit Zeigern vergleichen können. Der Compiler findet aber nicht die beiden operator== sondern nur die Funktion für die nicht beteiligte Klasse A.
glub.C: In function »int main()«: glub.C:34: Fehler: no match für »operator==« in »b == 0« glub.C:13: Anmerkung: Kandidaten sind: bool operator==(const A&, const A&) glub.C:36: Fehler: no match für »operator==« in »0 == b« glub.C:13: Anmerkung: Kandidaten sind: bool operator==(const A&, const A&)
-
std::cout << (b == (void*)0) << std::endl; std::cout << (b == d) << std::endl; std::cout << (static_cast<void*>(0) == b) << std::endl; // PC-Version std::cout << (d == b) << std::endl;Passt dir das nicht?
-
finix schrieb:
std::cout << (b == (void*)0) << std::endl; std::cout << (b == d) << std::endl; std::cout << (static_cast<void*>(0) == b) << std::endl; // PC-Version std::cout << (d == b) << std::endl;Passt dir das nicht?
Es funktioniert aber es ist nicht schön. Wäre gut, wenn man auf einen Cast verzichten könnte.
-
Ja, sicher nicht schön. Aber sich auf Biegen und Brechen gegen diesen Cast stemmen, so rein aus Prinzip? Geht ja ausschließlich um konstant 0.
Ansonsten: wie wär's mit nem
operator unspecified-bool-type()fürB?
-
finix schrieb:
Ja, sicher nicht schön. Aber sich auf Biegen und Brechen gegen diesen Cast stemmen, so rein aus Prinzip? Geht ja ausschließlich um konstant 0.
Ansonsten: wie wär's mit nem
operator unspecified-bool-type()fürB?Hmm. Wäre eine Überlegung wert.