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.
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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With