Does C++11 change the behavior of explicitly calling std::swap to ensure ADL-located swap's are found, like boost::swap?

后端 未结 4 1703
孤街浪徒
孤街浪徒 2020-12-01 10:32

Background

Consider for this question the following code:

#include 

namespace ns
{
    struct foo
    {
        foo() : i(0) {}
              


        
4条回答
  •  有刺的猬
    2020-12-01 11:00

    Here's a proof-of-concept implementation:

    #include 
    
    // exposition implementation
    namespace std_
    {
        namespace detail
        {
            // actual fallback implementation
            template 
            void swap(T& lhs, T& rhs)
            {
                T temp = std::move(lhs);
                lhs = std::move(rhs);
                rhs = std::move(temp);
            }
        }
    
        template 
        void swap(T& lhs, T& rhs)
        {
            using detail::swap; // shadows std_::swap, stops recursion
            swap(lhs, rhs); // unqualified call, allows ADL
        }
    }
    
    namespace ns
    {
        struct foo
        {
            foo() : i(0) {}
            int i;
    
        private:
            foo(const foo&); // not defined,
            foo& operator=(const foo&); // non-copyable
        };
    
        void swap(foo& lhs, foo& rhs)
        {
            std::swap(lhs.i, rhs.i);
        }
    }
    
    
    int main()
    {
        int i = 0, j = 0;
        std_::swap(i, j);
    
        ns::foo a, b;
        std_::swap(a, b);
    }
    

提交回复
热议问题