如何添加std :: swap为我的模板类? [英] How to add std::swap for my template class?

查看:143
本文介绍了如何添加std :: swap为我的模板类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何为我的类提供交换函数?




$ b $这里有一些问题,但很多矛盾(人A给解决方案A'有许多upvote人B说它是UB)或只有当编译器支持ADL才有效。



所以,假设我有以下模板(容器)类:

  template< typename T> 
class C {
// ...
void swap(C< T& y)throw(); // C x; x.swap(y);
}

那么什么是正确的方式来确保这个

  C< int> x,y; 
std :: swap(x,y);

请给出你对C ++ 03的回答,如果它仍然在C ++ 0x,更好!

解决方案

不允许在std命名空间中重载函数。 p>

将交换声明为自由函数,在与您的类 C 相同的命名空间中重载:

 模板< class T> 
void swap(C T& x,C T& y){x.swap(y); }

正确的交换方式是导入std :: swap并使用非限定版本这是通过基于命名空间的Koenig查找):

  template< class T> 
void dostuff(T x,T y){
...
使用std :: swap;
swap(x,y);
...
}

这将使用C :: swap if x对于没有自己交换的类型,它们是C和std :: swap。



(上面的std :: swap的导入只是必需的如果你知道你有一个C,那么你可以立即使用x.swap(y)w / o问题。)


Possible Duplicate:
how to provide a swap function for my class?

There are some questions about this, but a lot of contradictions (person A giving solution A' with many upvotes with person B saying it's UB) or "only works if the compiler supports ADL" is answered.

So, say I have the following template (container) class:

template<typename T>
class C {
    // ...
    void swap(C<T>& y) throw(); // C x; x.swap(y);
}

then what is the correct way to make sure this (example) code works:

C<int> x, y;
std::swap(x, y);

Please give your answer for C++03, and if it still works in C++0x, even better!

解决方案

You are not allowed to overload functions in the std-namespace.

Declare swap as a free function, overloaded in the same namespace as your class C:

 template<class T>
 void swap(C<T>& x, C<T>& y) { x.swap(y); }

The right way to swap is to import std::swap and use a non-qualified version (which is retreieved via namespace-based Koenig lookup):

 template<class T>
 void dostuff(T x, T y) {
    ...
    using std::swap;
    swap(x,y);
    ...
 }

That will use C::swap if x and are C, and std::swap for types that do not have their own swap.

(The import of std::swap like above is only necessary in template functions where the type is not known. If you know you have a C, then you can use x.swap(y) right away w/o problems.)

这篇关于如何添加std :: swap为我的模板类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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