Boost logo

Boost :

From: Pavel Chikulaev (pavel.chikulaev_at_[hidden])
Date: 2005-04-12 08:49:44


Hi boosters,

We often need to swap contents of two objects, but even more often we
need to swap contents with no-throw exception guarantee.

But currently we have no general way to swap two objects with no-throw
exception guarantee. What we do have now is std::swap, and member
functions which can be named swap, Swap, and so on. But now we can't
swap arbitary types with no-throw exception guarantee in a general way.

Yes, we can overload std::swap to support other than std:: types, but we
can't guarantee that invocation of std::swap won't throw.

So, I propose the following:

New traits classes:
 boost::is_swappable<T>::value,
 boost::is_nothrow_swappable<T>::value.
and specialize them for known types, but by default both should return false.

Introduce new function boost::nothrow_swap(T &, T &);
which will swap two objects if boost::is_nothrow_swappable<T>::value == true,
else compile-time error will occur.

Introduce new function boost::swap(T &, T &);
which will swap two objects if boost::is_swappable<T>::value == true,
else compile-time error will occur.

Introduce
template<typename T>
struct do_nothrow_swap
{
    static void nothow_swap (T &, T&);
}
and specialize it for types that can be swapped with no-throw guarantee
such as std::vector, invoking default
implementation will lead to compile-time error.

Introduce
template<typename T>
struct do_swap
{
    static void swap(T &, T &);
};
and specialize it for types that can be swapped(but without guarantees)
such as boost::array, invoking do_nothow_swap<T>::nothow_swap if
no specialization found.

Using this technique, we can support even such classes that doesn't have
swap member-function, but have Swap or any other.

I guess it would be helpful at least in boost::ptr_container library.

This gives new standard way to do the swapping work, and in contrast to
std::swap now we can be expilictly specify no-throw guarantee if needed.

As always any comments are appreciated.

P.S. Sorry if it was already proposed, didn't found it.

--
Pavel Chikulaev

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk