如何提供一个交换功能,我的课? [英] how to provide a swap function for my class?

查看:127
本文介绍了如何提供一个交换功能,我的课?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是正确的方法,使我的在STL算法交换

What is the proper way to enable my swap in STL algorithms?

1)会员交换。请问的std ::交换使用SFINAE技​​巧使用成员交换

1) Member swap. Does std::swap use SFINAE trick to use the member swap.

2)免费标准在同一个命名空间的交换

3)部分特。

3) Partial specialization of std::swap.

4)上述所有。

感谢你。

编辑:貌似我没有一句话,我的问题清清楚楚。基本上,我有一个模板类,我需要STL交易算法使用(有效)的交换方法我写了这个类。

Looks like I didn't word my question clearly. Basically, I have a template class and I need STL algos to use the (efficient) swap method I wrote for that class.

推荐答案

1)是正确的 调剂使用。写这种方式,当你想用库code和希望在交换启用ADL(参数相关的查找)。此外,此无关与SFINAE

1) is the proper use of swap. Write it this way when you write "library" code and want to enable ADL (argument-dependent lookup) on swap. Also, this has nothing to do with SFINAE.

// some algorithm in your code
template<class T>
void foo(T& lhs, T& rhs){
  using std::swap; // enable 'std::swap' to be found
                   // if no other 'swap' is found through ADL
  // some code ...
  swap(lhs, rhs); // unqualified call, uses ADL and finds a fitting 'swap'
                  // or falls back on 'std::swap'
  // more code ...
}


2)的正确方法是为你的类提供了一个交换的功能。


2) Is the proper way to provide a swap function for your class.

namespace Foo{

class Bar{}; // dummy

void swap(Bar& lhs, Bar& rhs){
  // ...
}

}

如果交换现在使用如图1),你的函数会被发现。此外,您还可以使该功能的朋友,如果你确实需要,或提供一个成员交换被调用free函数:

If swap is now used as shown in 1), your function will be found. Also, you may make that function a friend if you absolutely need to, or provide a member swap that is called by the free function:

// version 1
class Bar{
public:
  friend void swap(Bar& lhs, Bar& rhs){
    // ....
  }
};

// version 2
class Bar{
public:
  void swap(Bar& other){
    // ...
  }
};

void swap(Bar& lhs, Bar& rhs){
  lhs.swap(rhs);
}


3)你的意思是明确的专业化。部分仍是别的东西,也不可能功能,只有结构/班。这样,因为你不能专注的std ::交换模板类,你的有无的在您的命名空间提供了一个免费的功能。不是坏事,如果我可以这么说。现在,一个明确的专业化也有可能,但一般你不想专门函数模板


3) You mean an explicit specialization. Partial is still something else and also not possible for functions, only structs / classes. As such, since you can't specialize std::swap for template classes, you have to provide a free function in your namespace. Not a bad thing, if I may say so. Now, an explicit specialization is also possible, but generally you do not want to specialize a function template:

namespace std
{  // only allowed to extend namespace std with specializations

template<> // specialization
void swap<Bar>(Bar& lhs, Bar& rhs){
  // ...
}

}


4)否,如1)是从2个不同)和3)。而且,具有两个2)和3)将导致总是具有2)拾取,因为它适合更好


4) No, as 1) is distinct from 2) and 3). Also, having both 2) and 3) will lead to always having 2) picked, because it fits better.

这篇关于如何提供一个交换功能,我的课?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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