C++,重载 std::swap,编译器错误,VS 2010

标签 c++ visual-studio-2010 overloading swap

我想在我的模板类中重载 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/

相关文章:

asp.net - 将 Visual Studio 切换为使用本地 IIS 服务器后,找不到图像和样式文件

c# - 如何在一个带有被动重载的大方法和一堆小的重载之间做出选择,每个方法都做少量的工作?

c++ - 在派生类的对象上使用指向基类成员函数的指针

c++ - 生成文件 | Make 后清理 - 错误 : No such file or directory | Error: recipe for target * failed

c++ - 通用 Constexpr 查找表 C++11

typescript - TypeScript 中的构造函数重载

C++:如何从我自己的函数中的头文件中调用一个函数(比如 funA()),它的名字也是 funA()?

c++ - 当 C/C++ 中的数字常量以 0 为前缀时,这意味着什么?

visual-studio - 加载从TFS服务器检索的项目时,如何解决错误消息 “an error occurred registering this project with source control”?

visual-studio-2010 - 重新关联 Visual Studio 2012 的文件类型