Reputation: 35
In getting a error using template functions in that generic swap function:
#include <iostream>
#include <complex>
using namespace std;
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;
return 0;
}
Someone can spot a error here? I getting the error at the three calling functions:
Error C2668 'swap': ambiguous call to overloaded function
I changed to std:: format, that the code:
#include <iostream>
#include <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;
std::complex<double> r(2.4, 3.5), s(3.4, 6.7);
std::cout << "inputs: " << m << "," << n << std::endl;
swap(m, n);
std::cout << "outputs: " << m << "," << n << std::endl;
std::cout << "double inputs: " << x << "," << y << std::endl;
swap(x, y);
std::cout << "double outputs: " << x << "," << y << std::endl;
std::cout << "complex inputs: " << r << "," << s << std::endl;
swap(r, s);
std::cout << "complex outputs: " << r << "," << s << std::endl;
return 0;
}
And now the full error I got:
SwapFunction.cpp(55,14): error C2668: 'swap': ambiguous call to overloaded function
SwapFunction.cpp(32,13): message : could be 'void swap<std::complex<double>>(T &,T &)'
with
[
T=std::complex<double>
]
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333\include\utility(102,19): message : or 'void std::swap<std::complex<double>,0>(_Ty &,_Ty &) noexcept(<expr>)' [found using argument-dependent lookup]
with
[
_Ty=std::complex<double>
]
So I only getting error in the std::complex<double>
call function, whats can be done next?
Upvotes: 0
Views: 514
Reputation: 25388
using namespace std
is the likely culprit here, since it pulls std::swap
into the global namespace.
So you can either remove that and fully qualify the relevant identifiers (recommended) or rename your own swap
function.
Upvotes: 3