In C++20, there are two swap
function templates: std::ranges::swap(T&&, U&&)
and std::swap(T&, T&)
.
I just wonder:
What's the difference between they two?
In C++20, there are two swap
function templates: std::ranges::swap(T&&, U&&)
and std::swap(T&, T&)
.
I just wonder:
What's the difference between they two?
std::swap
has a problem. It's possible that there is a more efficient swap function that is not in the std
namespace. You should enable ADL to find and use that if available and use std::swap
otherwise. It's called "std 2-step":
using std::swap;
swap(a, b);
But std::ranges::swap
doesn't have this problem and will call the version ADL would have called:
std::ranges::swap(a, b);
Here is a demonstration.
In rough terms: std::ranges::swap
generalizes std::swap
.
T
and U
are the same, then it's equivalent to invoking std::swap
.See the cppreference page for details.
I must say I find this function to be somewhat confusing and baroque, but then - maybe people more experienced with the range library develop an intuition as to why it makes sense.