swap

类的swap
#include <vector>
#include <memory>

class WidgetImpl
{
public:
    WidgetImpl() = default;
    ~WidgetImpl() = default;

private:
    int m_a, m_b, m_c;
    std::vector<double> m_v;
};

class Widget
{
public:
    Widget() : m_Impl(new WidgetImpl){}
    ~Widget()= default;
    Widget & operator=(const Widget & rhs)
    {
        *m_Impl = *(rhs.m_Impl);
        return *this;
    }

    void swap(Widget &other) {
        std::swap(m_Impl, other.m_Impl);
    }

private:
    std::shared_ptr<WidgetImpl> m_Impl;
};

// 通常不允许改变std命名空间内的任何东西,但可以为标准templates(如swap)制造特化版本
namespace std {
    template<>  // 表示是std::swap的一个total template specialization版本
    void swap<Widget>(Widget &a, Widget &b) // 函数名之后的<Widget>表示这一特化版本针对"T是Widget"而设计
    {
        a.swap(b);
    }
}
using namespace std;
int main() {
    Widget aw;
    Widget bw;
    swap(aw, bw);

    return 0;
}
class templates的swap
#include <vector>
#include <memory>

namespace WidgetStuff
{
    template<typename T>
    class WidgetImpl
    {
    public:
        WidgetImpl() = default;
        ~WidgetImpl() = default;

    private:
        T m_a, m_b, m_c;
        std::vector<T> m_v;
    };

    template<typename T>
    class Widget
    {
    public:
        Widget() : m_Impl(new WidgetImpl<T>) {}
        ~Widget() = default;
        Widget & operator=(const Widget & rhs)
        {
            *m_Impl = *(rhs.m_Impl);
            return *this;
        }

        void swap(Widget &other) {
            std::swap(m_Impl, other.m_Impl);
        }

    private:
        std::shared_ptr<WidgetImpl<T> > m_Impl;
    };

    template<typename T>
    void swap(Widget<T> &a, Widget<T> &b)
    {
        a.swap(b);
    }
}

#if 0  // 重载function templates没有问题,但在std里实现是跨越红线的行为,虽然仍可编译和运行。
namespace std {
    template<typename T>
    void swap(WidgetStuff::Widget<T> &a, WidgetStuff::Widget<T> &b)
    {
        a.swap(b);
    }
}
#endif

using namespace std;

int main() {
    WidgetStuff::Widget<int> aw;
    WidgetStuff::Widget<int> bw;
    swap(aw, bw);  // 实际调用的是WidgetStuff::swap,不需要显示写成WidgetStuff::swap(aw, bw);
                   // 依据Koenig Lookup/Argument Dependent Lookup (ADL)
                   // 来从aw和bw所在的namespace中找到WidgetStuff::swap

    int a = 2, b = 3;
    swap(a,b);    // 实际调用的是std::swap

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值