Re: rvalue swap confusion
On 17 Apr., 07:04, SG <s.gesem...@gmail.com> wrote:
I honestly don't understand the motivation for LWG issue #770. You
can still swap an rvalue with an lvalue by invoking the swap member
function on the rvalue. It even works in C++98:
vector<int> source();
vector<int> a;
source().swap(a);
....come to think of it, providing a free swap function that takes only
lvalues as arguments can be all you need to do. From what I
understand it's possible to add "rvalue swap support" for *free* for
all user-defined types.
Suppose, std::swap is overloaded. One version accepts lvalue
arguments only and the 2nd version accepts rvalues as well. In that
case a swap involving an rvalue resolves to the a std::swap function
which accepts an rvalue and forwards its parameters to a swap function
that taking two lvalue arguments (which might be a user-provided swap
function).
The std::swap funciton template overloads might look like this:
template<typename T>
requires MoveConstructible<T>
&& MoveAssignable<T>
void swap(T & x, T & y) // <-- default swap for two lvalues
{
T temp ( move(x) );
x = move(y);
y = move(temp);
}
template<typename X, typename Y>
requires HasSwap<X&,Y&> // forward to "lvalue-swap"
&& !SameType<X&&,Y&&> // avoid ambiguities & recursion
inline void swap(X && x, Y && y) // accept lvalues and rvalues
{
swap(x,y); // call some swap function that takes two lvalues
}
This would automatically render every type T that models Swappable<T>
(Swappable<T> refines HasSwap<T&,T&>) also swappable with rvalues for
*free* (HasSwap<T,T&&> and HasSwap<T&&,T>) without specific user-
supplied overloads.
Note: the requirement !SameType<X&&,Y&&> above avoids ambiguities
(can't be both lvalue references of the same type) and also doesn't
allow swapping *two* rvalues of the same type. The latter restriction
is of no advantage since swapping two rvalues is useless.
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]