C++, overloading std::swap, compiler error, VS 2010

Posted by Ian on Stack Overflow See other posts from Stack Overflow or by Ian
Published on 2011-01-02T21:13:14Z Indexed on 2011/01/02 21:53 UTC
Read the original article Hit count: 153

I would like to overload std::swap in my template class. In the following code (simplified)

#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

there is a compiler error (only in VS 2010):

error C2668: 'std::swap' : ambiguous call to overloaded 

I do not know why, std::swap should be overoaded... Using g ++ code works perfectly. Without templates (i.e. Point2D is not a template class) this code also works..

Thanks for your help.

© Stack Overflow or respective owner

Related posts about c++

Related posts about visual-studio-2010