swap für eingenen Type korrekt implementieren
-
Hallo,
ich würde gerne eine eigene sawp Funktion für meine Klasse haben welche sich in einem eigenen Namespace befindet.
nur wir macht man das korrekt?- Als Memberfunction der Klasse ein swap(MyClass& other)
- eine eigene swap function, wenn dann in welchen Namespace
- std::swap überladen
- sonstiges
vielen Dank für die Hilfe!
-
Ich rate dir zur dritten Variante, dann wird das Ganze auch bei Templates funktionieren, welche auf std::swap setzen.
Was hast du vor? Vielleicht brauchts auch nur einen Moveoperator/konstruktor.
-
http://en.cppreference.com/w/cpp/algorithm/swap schrieb:
Specializations
std::swap may be specialized in namespace std for user-defined types, but such specializations are not found by ADL (the namespace std is not the associated namespace for the user-defined type). The expected way to make a user-defined type swappable is to provide a non-member function swap in the same namespace as the type: see Swappable for details.
-
danke für den Hilfstext manni66
so scheint es zu funktionieren
namespace ns { class Foo { friend void swap (Foo& a, Foo&b) noexcept; // ... // Implementation Details tun nix zur Sache } ; void swap (Foo& a, Foo&b) noexcept ; //und natürlich auch irgendwo implementieren ... }damit ruft ein std::sort von einem vector<Foo> meine swap Implementation auf.