Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

specializing std::swap for rvalues

Tags:

c++

c++11

In the standard (20.2.2 [utility.swap]), std::swap is defined for lvalue references. I understand that this is the common case for when you want to swap two things. However, there are times when it's correct and desirable to swap rvalues (when temporary objects contain references, like here: swap temporary tuples of references).

Why isn't there an overload for rvalues? Does the risk of doing a meaningless swap on rvalues outweigh the potential benefits?

Is there a legal way to support swapping rvalue std::tuple objects which contain references? For a user defined type, I would specialize swap to accept its arguments by value, but it doesn't seem kosher to do the same for a library type like std::tuple.

like image 742
Ben Jones Avatar asked Feb 27 '14 20:02

Ben Jones


1 Answers

How about instead creating an lvalue_cast utility function that casts an rvalue to an lvalue:

#include <tuple>
#include <iostream>

template <class T>
T&
lvalue_cast(T&& t)
{
    return t;
}

int
main()
{
    int i = 1;
    int j = 2;
    swap(lvalue_cast(std::tie(i)), lvalue_cast(std::tie(j)));
    std::cout << i << '\n';
    std::cout << j << '\n';
}
like image 99
Howard Hinnant Avatar answered Oct 09 '22 13:10

Howard Hinnant