Providing a Swap Function for STL Algorithms
To enable the use of a custom swap method in STL algorithms, there are several approaches:
Member Swap:
Free-Standing Swap Function:
Explicit Specialization of std::swap:
Recommended Approach:
The recommended approach is to use a free-standing swap function in the same namespace as the class. This allows the use of ADL (Argument-Dependent Lookup) when calling swap within STL algorithms.
Example:
namespace Foo { class Bar{}; // dummy void swap(Bar& lhs, Bar& rhs) { // ... } }
Using the above swap function within an STL algorithm:
template<class T> void foo(T& lhs, T& rhs) { using std::swap; // enable 'std::swap' to be found // if no other 'swap' is found through ADL // some code ... swap(lhs, rhs); // unqualified call, uses ADL and finds a fitting 'swap' // or falls back on 'std::swap' // more code ... }
The above is the detailed content of How Can I Provide a Custom Swap Function for Use with STL Algorithms?. For more information, please follow other related articles on the PHP Chinese website!