asit_dhal asit_dhal - 3 months ago 21
C++ Question

ambiguous call in template error

Can anyone tell me the cause of error ?

Error is

C:\web\template1.cpp||In function 'int main()':|
C:\web\template1.cpp|23|error: call of overloaded 'swap(int&, int&)' is ambiguous|
C:\web\template1.cpp|6|note: candidates are: void swap(X&, X&) [with X = int]|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\include\c++\bits\move.h|76|note: void std::swap(_Tp&, _Tp&) [with _Tp = int]|
C:\web\template1.cpp|24|error: call of overloaded 'swap(double&, double&)' is ambiguous|
C:\web\template1.cpp|6|note: candidates are: void swap(X&, X&) [with X = double]|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\include\c++\bits\move.h|76|note: void std::swap(_Tp&, _Tp&) [with _Tp = double]|
C:\web\template1.cpp|25|error: call of overloaded 'swap(char&, char&)' is ambiguous|
C:\web\template1.cpp|6|note: candidates are: void swap(X&, X&) [with X = char]|
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\include\c++\bits\move.h|76|note: void std::swap(_Tp&, _Tp&) [with _Tp = char]|
||=== Build finished: 3 errors, 0 warnings ===|





#include <iostream>

using namespace std;

template <typename X>
void swap(X &a, X &b)
{
X temp = a;
a = b;
b = temp;
}

int main()
{
int i=10, j=20;
double x=10.1, y=23.3;
char a='x', b='z';

cout<<"i="<<i<<"\tj="<<j<<endl;
cout<<"x="<<x<<"\ty="<<y<<endl;
cout<<"a="<<a<<"\tb="<<b<<endl;

swap(i,j);
swap(x,y);
swap(a,b);

cout<<"i="<<i<<"\tj="<<j<<endl;
cout<<"x="<<x<<"\ty="<<y<<endl;
cout<<"a="<<a<<"\tb="<<b<<endl;

return 0;
}

Answer

Your swap conflicts with std::swap. Remove using namespace std; above and correct the rest code from std namespace.

std::cout<<"i="<<i<<"\tj="<<j<<std::endl;
std::cout<<"x="<<x<<"\ty="<<y<<std::endl;
std::cout<<"a="<<a<<"\tb="<<b<<std::endl;

Also it's worth reading Why is 'using namespace std;' considered a bad practice in C++?

Comments