Reputation: 539
What is the standard way of calling swap() for arguments defined by template?
Obviously calling std::swap()
is not correct, as it would not pick up the swap declared in the same namespace as the type.
It seems that inserting a using namespace std;
is not correct as it leads to errors.
Should one insert a using std::swap;
?
Upvotes: 0
Views: 127
Reputation: 40836
The standard requirement for "swappable types" is swap(t, u)
where std::swap
from the <utility>
header is a viable candidate.
This is satisfied by both using namespace std;
and if a using std::swap;
. The standard way given is the latter (https://wg21.link/swappable.requirements#6):
#include <utility>
// Preconditions: std::forward<T>(t) is swappable with std::forward<U>(u).
template<class T, class U>
void value_swap(T&& t, U&& u) {
using std::swap;
swap(std::forward<T>(t), std::forward<U>(u)); // OK, uses “swappable with'' conditions
// for rvalues and lvalues
}
// Preconditions: lvalues of T are swappable.
template<class T>
void lv_swap(T& t1, T& t2) {
using std::swap;
swap(t1, t2); // OK, uses swappable conditions for lvalues of type T
}
For swapping two lvalues of the same type, you can also use std::iter_swap(std::addressof(a), std::adddressof(b))
. This won't need a using-declaration.
See also: std::is_swappable
.
This is separate from the C++20 concept swappable
, which uses std::ranges::swap
, though that might be what you want to use.
Upvotes: 1