如何重载std :: swap() [英] How to overload std::swap()

查看:272
本文介绍了如何重载std :: swap()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: swap()被许多std容器使用(例如 std :: list

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

但是,交换的std实现方法是code> std :: vector

因此,通过重载 std ::可以获得更高的效率swap()使用自定义类型特定实现。但是如何实现它,所以它将被std容器使用?

Thus efficiency can be gained by overloading std::swap() with a custom type specific implementation. But how can you implement it so it will be used by the std containers?

推荐答案

正确的方式重载交换是写它在与要交换的相同的命名空间中,以便可以通过参数相关查找(ADL)找到它。一个特别容易做的事是:

The right way to overload swap is to write it in the same namespace as what you're swapping, so that it can be found via argument-dependent lookup (ADL). One particularly easy thing to do is:

class X
{
    // ...
    friend void swap(X& a, X& b)
    {
        using std::swap; // bring in swap for built-in types

        swap(a.base1, b.base1);
        swap(a.base2, b.base2);
        // ...
        swap(a.member1, b.member1);
        swap(a.member2, b.member2);
        // ...
    }
};

这篇关于如何重载std :: swap()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆