Boost logo

Boost Users :

From: Joseph Gauterin (joseph.gauterin_at_[hidden])
Date: 2008-08-18 18:07:53


Hi Terry,
>How should a user/developer like me implement a custom swap so that users
>get the benefit of my::swap, then boost::swap, and finally std::swap without
>putting too much burden on my user.
In the same way that swap functions are currently provided: either a
specilization of std::swap or a 'swap' function in the same namespace
as a UDT.

>If the user does this...
>using namespace std;
>using namespace boost;
>using namespace my;
>And then somewhere in his code...
> HisType a = MakeA();
> HisType b = MakeB();
> swap(a, b); // Unqualified? Or should the user specify a namespace?
> Which one?

A call to std::swap will swap the two values using temporary values
and assignments.
A call to boost::swap will call my::swap using argument dependent lookup.
A call to my::swap will just call my::swap.
An unqualified call to swap will call my::swap using argument dependent lookup.

>If the user has his own swap(HisType, HisType) invoke that.
>Otherwise, if HisType.swap() exists, then use that.
>Otherwise, use my::swap() if its "better" than boost::swap
>Otherwise, use boost::swap(), if its "better" than std::swap
>Otherwise, just use std::swap().

boost::swap calls my::swap() if it exists, else it calls std::swap().
HisType.swap is not considered directly.

>Sorry about all the ambiguity. But that's the real problem, isn't it?
Indeed - but we're using a trick to make sure that boost::swap is
never ambiguous with std::swap.

So:
using namespace std;
using namespace boost;
swap(a, b);
Will call a function called swap in the namespace where 'a' is
declared if it exists (adl), or std::swap otherwise. It will never
call boost::swap.

std::swap(a, b);
Will swap 'a' and 'b' using temporaries and assignments.

boost::swap(a, b);
Will call a function called swap in the namespace where 'a' is
declared if it exists, or std::swap otherwise. No 'using' statements
or declarations are required.

Joe.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net