templates swap function error


Hello ,
I am new to cpp and doing a simple template swap program:

#include<iostream>
using namespace std;
template<class T>

void swap(T &a,T &b)
{
T c=a;
a=b;
b=c;
}
int main()
{
int a=10,b=20;
cout<<a<<" "<<b<<endl;
swap(a,b);
cout<<a<<" "<<b<<endl;

system("pause");
return 0;
}

The error is : Error 1 error C2668: 'swap' : ambiguous call to overloaded function

I don't know why this is happening.
Please give me solution..
> 'swap' : ambiguous call to overloaded function

See: http://www.cplusplus.com/reference/algorithm/swap/

This is one way of removing the ambiguity.
1
2
// swap(a,b) ;
::swap(a,b) ;
The reason of the error is your directive using namespace std; You placed names from this name space and among them the name swap into global namespace. When you call swap without qualificztion the compiler does not know which function to call either your function or std::swap You can explicitly specify that you are going to use your function
::swap( a, b );
Last edited on
Here's another solution. Replace
using namespace std;
with
using std::cout; using std::endl;

Last edited on
Topic archived. No new replies allowed.