繁体   English   中英

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

[英]C++, overloading std::swap, compiler error, VS 2010

我想在模板类中重载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() 基本上,您可以对std :: swap进行特殊化,但不能对它进行重载。

因此,可以为特定的Point<>类型(例如Point<float> )创建特定版本,但不能为任何Point<T>创建特定版本。

我知道您没有问过这个问题,但是由于您使用的是VC10,因此提供移动构造函数移动赋值运算符应该使std::swap()对您的类型表现最佳。

之所以模棱两可,是因为您提供了:: swap和std :: swap,然后using 'd std :: swap。 现在,全局命名空间中既有:: swap也有std :: swap。 因此,编译器不知道您是指:: swap还是std :: swap。

但是,提供移动操作员/构造函数将使交换在现实中达到最佳性能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM