C++ swap function template

Sep 12, 2008 at 2:25am
Could someone tell me why the first 2 calls on swap will not compile and how to fix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>
#include<string>
using namespace std;

template <class T>
void swap(T& x,T& y)
{
     T temp;
     temp=x;
     x=y;
     y=temp;
}
int main()
{
   int a=44 ;
   int b=66 ;
   float s=4.4;
   float t=6.6;
   string mr="George";
   string ms="Martha";
   cout<<"Before swap a: "<<a<<" b: "<<b<<endl;
   swap(a,b);
   cout<<"After swap a: "<<a<<" b: "<<b<<endl;
   cout<<"Before swap s: "<<s<<" t: "<<t<<endl;
   swap( s, t );
   cout<<"After swap s: "<<s<<" t: "<<t<<endl;
   
   cout<<"Before swap mr: "<<mr<<" ms: "<<ms<<endl; 
   swap(mr,ms);
   cout<<"After swap mr: "<<mr<<" ms: "<<ms<<endl;
system("pause");
return 0;
} 

the error says " the call on the overloaded swap function is ambiguous"
Note: if the 1st 2 calls are commented out it will compile and the last swap call works.
Sep 12, 2008 at 2:46am
The STL already defines a template function named swap, so the compiler thinks you are overloading it. Both your function and theirs take two parameters of type T so the compiler is not sure whether to use your function or theirs.

The simplest fix would probably be to rename your function.
Sep 12, 2008 at 3:06am
Another way is to pass pointers to your function, instead of references. It will work all the same, you'll just have a little more syntax.
Sep 12, 2008 at 7:00am
Thanks Zhuge i renamed it and it compiled immediately and works properly
Thanks helios will have a play round with pointers and see what i can learn
Topic archived. No new replies allowed.