【发布时间】:2011-01-02 21:13:14
【问题描述】:
我想在我的模板类中重载 std::swap。在以下代码中(简化)
#ifndef Point2D_H
#define Point2D_H
template <class T>
class Point2D
{
protected:
T x;
T y;
public:
Point2D () : x ( 0 ), y ( 0 ) {}
Point2D( const T &x_, const T &y_ ) : x ( x_ ), y ( y_ ) {}
....
public:
void swap ( Point2D <T> &p );
};
template <class T>
inline void swap ( Point2D <T> &p1, Point2D <T> &p2 ) { p1.swap ( p2 ); }
namespace std
{
template <class T>
inline void swap ( Point2D <T> &p1, Point2D <T> &p2 ) { p1.swap ( p2 ); }
}
template <class T>
void Point2D <T>::swap ( Point2D <T> &p )
{
using (std::swap);
swap ( x, p.x );
swap ( y, p.y );
}
#endif
存在编译器错误(仅在 VS 2010 中):
error C2668: 'std::swap' : ambiguous call to overloaded
我不知道为什么,std::swap 应该被过度加载...使用 g ++ 代码可以完美地工作。如果没有模板(即 Point2D 不是模板类),此代码也可以工作..
感谢您的帮助。
【问题讨论】:
-
你不应该重载
std::swap,你应该专门化它。对 villintehaspam 所链接问题的回答解释了这种区别并举例说明。但是部分特化对于函数模板是不可能的,所以你必须在你自己的命名空间中定义你的实现并依赖 Koenig 查找。 -
注意:标准规定“显式特化声明不应是友元声明”。不过这是个好主意。
标签: c++ visual-studio-2010 overloading swap