[C++] Advice on custom swap function pls

Started by
1 comment, last by Nitage 17 years, 8 months ago
I've come up with a small swap function for use in generic code. It's based on the standard adl swap trick, but it's designed to be used in situations where you only really need to assign, but you want to be able to take advantage of specialized swap functions where they exists. For example, swapping two vectors is much faster than assigning one to the other, and is equivilent if you don't care about the end value of the right parameter. Does anyone have any comments/constructive criticisms?

namespace detail
{
    //called swap even though it assigns - ugly but necessary
    template< class T >
    void swap(T& left, T& right)
    {
        left = right;
    }
}

//Uses ADL to pick out any specialized swap algorithms, defaulting to the assigning 'swap'
template< class T >
void swap_or_assign(T& left, T& right)
{
    using detail::swap;
    swap(left,right);
}


Advertisement
The name is confusing, in my opinion (EDIT: maybe something like "transfer" would be more adapted). Also, wouldn't the use of a pointer or reference accomplish the same thing without assignments and/or swaps?
The original purpose of it was to be used to remove items from a vector in which ordering wasn't important using the technique the last element is copied over the one to be erased, then pop_back is called.

I realised that it would probably be quicker to swap objects that provided a custom swap function, but three times as slow and require a temporary variable in the case where no custom swap existed. - this is my attempt to automatically choose the best way at compile time.

It has some problems (like any class declared in namespace std will still use the generic std::swap algorithm and there's no guarentee that a custom swap will be faster than a single assignment) but I think it could be useful.

I like the name 'transfer' much better than 'swap_or_assign' as well.

Thanks for the comments.

This topic is closed to new replies.

Advertisement