用户定义类型的重载全局交换 [英] Overloading global swap for user-defined type

查看:155
本文介绍了用户定义类型的重载全局交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准禁止在命名空间 std 中声明类型或定义任何内容,但它允许您为用户定义类型专门化标准STL模板。

The C++ standard prohibits declaring types or defining anything in namespace std, but it does allow you to specialize standard STL templates for user-defined types.

通常,当我想为自己的自定义模板类型专门化 std :: swap 时,我只需:

Usually, when I want to specialize std::swap for my own custom templated type, I just do:

namespace std
{
  template <class T>
  void swap(MyType<T>& t1, MyType<T>& t2)
  {
     t1.swap(t2);
  }
}

...但我不完全确定我的惯例是否符合标准。我是这样做的吗?

...and that works out fine. But I'm not entirely sure if my usual practice is standard compliant. Am I doing this correctly?

推荐答案

你有什么不是一个专业化,它是重载,正是什么标准禁止。 (

What you have is not a specialization, it is overloading and exactly what the standard prohibits. (However, it will almost always currently work in practice, and may be acceptable to you.)

以下是为您的课程模板提供自己的互换功能的方法:

Here is how you provide your own swap for your class template:

template<class T>
struct Ex {
  friend void swap(Ex& a, Ex& b) {
    using std::swap;
    swap(a.n, b.n);
  }
  T n;
}

这里是如何调用swap,你会注意到Ex的交换太:

And here is how you call swap, which you'll notice is used in Ex's swap too:

void f() {
  using std::swap; // std::swap is the default or fallback
  Ex<int> a, b;
  swap(a, b); // invokes ADL
}

相关:功能模板专业化重要性和必要性

这篇关于用户定义类型的重载全局交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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