Jump to content
  • Advertisement
Sign in to follow this  
Nitage

[C++] Advice on custom swap function pls

This topic is 4354 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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);
}


Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!