任意の 2 つの変数を交換するために、この単純な C++ コードを作成しました。int と double では機能しますが、複素数では機能しません。なぜですか?
#include <iostream>
#include <complex>
using std::cout;
using std::endl;
using std::complex;
template <class T>
inline void swap(T& d, T& s)
{
T temp = d;
d = s;
s = temp;
}
int main()
{
int m=5, n=10;
double x=5.3, y=10.6;
complex<double> r(2.4, 3.5), s(3.4, 6.7);
cout << "inputs: " << m << " , " << n << endl;
swap(m, n);
cout << "outputs: " << m << " , " << n << endl;
cout << "double inputs: " << x << " , " << y << endl;
swap(x, y);
cout << "double outputs: " << x << " , " << y << endl;
cout << "complex inputs: " << r << " , " << s << endl;
swap(r, s);
cout << "complex outputs: " << r << " , " << s << endl;
}
これはエラーです:
g++ 02.swap.template.cpp -o c.out.02
02.swap.template.cpp: In function ‘int main()’:
02.swap.template.cpp:37:13: error: call of overloaded ‘swap(std::complex<double>&, std::complex<double>&)’ is ambiguous
02.swap.template.cpp:37:13: note: candidates are:
02.swap.template.cpp:13:13: note: void swap(T&, T&) [with T = std::complex<double>]
/usr/include/c++/4.6/bits/move.h:122:5: note: void std::swap(_Tp&, _Tp&) [with _Tp = std::complex<double>]