Search code examples
c++stlstandardsc++20std-ranges

What's the difference between std::ranges::swap() and std::swap()?


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?


Solution

  • In rough terms: std::ranges::swap generalizes std::swap.

    • If T and U are the same, then it's equivalent to invoking std::swap.
    • Otherwise it will swap the arguments as two ranges - if they're ranges.
    • Otherwise it will perform a swap-like procedure with move assignment between the different types T and U.
    • If even that can't happen, it will fail to compile.

    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.