How to overload std::swap()

后端 未结 4 1859
迷失自我
迷失自我 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:40

    While it's correct that one shouldn't generally add stuff to the std:: namespace, adding template specializations for user-defined types is specifically allowed. Overloading the functions is not. This is a subtle difference :-)

    17.4.3.1/1 It is undefined for a C++ program to add declarations or definitions to namespace std or namespaces with namespace std unless otherwise specified. A program may add template specializations for any standard library template to namespace std. Such a specialization (complete or partial) of a standard library results in undefined behaviour unless the declaration depends on a user-defined name of external linkage and unless the template specialization meets the standard library requirements for the original template.

    A specialization of std::swap would look like:

    namespace std
    {
        template<>
        void swap(myspace::mytype& a, myspace::mytype& b) { ... }
    }
    

    Without the template<> bit it would be an overload, which is undefined, rather than a specialization, which is permitted. @Wilka's suggest approach of changing the default namespace may work with user code (due to Koenig lookup preferring the namespace-less version) but it's not guaranteed to, and in fact isn't really supposed to (the STL implementation ought to use the fully-qualified std::swap).

    There is a thread on comp.lang.c++.moderated with a long dicussion of the topic. Most of it is about partial specialization, though (which there's currently no good way to do).

提交回复
热议问题