我想在我的模板类中重载 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 不是模板类),此代码也可以工作..
感谢您的帮助。
最佳答案
请参阅How to overload std::swap() .基本上,您可以对 std::swap 进行特化,但不能进行重载。
因此,可以为特定的 Point<>
创建特定的版本类型(例如 Point<float>
),但不适用于任何 Point<T>
.
关于C++,重载 std::swap,编译器错误,VS 2010,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4580547/