0

I want to write an overload of swap that I expect the compiler to find through ADL. This version of swap can swap two arguments of different types, with the types being defined in the same namespace. This is what I thought might work:

#include <utility>

namespace mynamespace
{
    struct FirstStruct
    {
    };

    struct SecondStruct
    {
    };

    template<typename first_t, typename second_t>
    void swap(first_t&&, second_t&&)
    {
        ...
    }
}

I use a universal reference because I want it to work with both r-value refs (temporaries) as well as l-value refs.

However, this, and many other variants I've tried in an attempt to avoid having to write a multitude of specialized overloads, doesn't seem to work, especially when a using std::swap is specified before making an unqualified call to swap, which is what I expect most users would do.

Do I have no other option but to write 4 x 4 = 16 variants of swap?

TripShock
  • 4,081
  • 5
  • 30
  • 39

1 Answers1

1

You just need 3 overloads:

template<typename first_t, typename second_t>
void swap(first_t&&, second_t&&)
{
    //...
}

 // for better match than std::swap
 void swap(FirstStruct& lhs, FirstStruct& rhs) { swap<FirstStruct&, FirstStruct&>(lhs, rhs); }
 void swap(SecondStruct& lhs, SecondStruct& rhs) { swap<SecondStruct&, SecondStruct&>(lhs, rhs); }

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302