我编写了这个简单的 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>]