How to provide swap() for a class in the global namespace?

150 Views Asked by At

For a class in a namespace the proper way to provide swap() is to define a free function in that namespace (e.g. How to overload std::swap()). But what is the best practice for a class that's in the global namespace?

cppreference has an example with a free swap() function in the global namespace.
But this is the only place I've seen that done and I worry this was just an oversight.

2

There are 2 best solutions below

2
Deduplicator On BEST ANSWER

In general, no library should use the global namespace, only the main application. And even that rarely, who knows when you will make part of it its own library?

Aside from that, the global scope :: is a namespace like any other, thus if you define a type there, the associated free functions belong there too.
Otherwise, argument-dependent lookup cannot find them.

0
Swoope On

I think you can just define a swap overload in the same namespace as the class, even if it's in the global namespace. Are you looking for something like this?

#include <iostream>
#include <utility>

struct S {
    void swap(S& other)
    {
        using std::swap;
        swap(data, other.data);
    }
    int data;
};

void swap(S& lhs, S& rhs)
{
    lhs.swap(rhs);
}

int main()
{
    using std::swap;
    S a = { 10 }, b = { 20 };
    std::cout << a.data << ' ' << b.data << std::endl;
    swap(a, b);
    std::cout << a.data << ' ' << b.data << std::endl;
    return 0;
}

Notice the using std::swap in main. So if you comment out the swap overload for the class, the code will fallback to std::swap.