How to overload std::swap()

后端 未结 4 1919
迷失自我
迷失自我 2020-11-22 15:00

std::swap() is used by many std containers (such as std::list and std::vector) during sorting and even assignment.

But the std

4条回答
  •  攒了一身酷
    2020-11-22 15:30

    You're not allowed (by the C++ standard) to overload std::swap, however you are specifically allowed to add template specializations for your own types to the std namespace. E.g.

    namespace std
    {
        template<>
        void swap(my_type& lhs, my_type& rhs)
        {
           // ... blah
        }
    }
    

    then the usages in the std containers (and anywhere else) will pick your specialization instead of the general one.

    Also note that providing a base class implementation of swap isn't good enough for your derived types. E.g. if you have

    class Base
    {
        // ... stuff ...
    }
    class Derived : public Base
    {
        // ... stuff ...
    }
    
    namespace std
    {
        template<>
        void swap(Base& lha, Base& rhs)
        {
           // ...
        }
    }
    

    this will work for Base classes, but if you try to swap two Derived objects it will use the generic version from std because the templated swap is an exact match (and it avoids the problem of only swapping the 'base' parts of your derived objects).

    NOTE: I've updated this to remove the wrong bits from my last answer. D'oh! (thanks puetzk and j_random_hacker for pointing it out)

提交回复
热议问题