Please help. I am unable to find the error !!

#include <iostream>
using namespace std;
template <class T>
void swap(T&x, T&y)
{ T temp=x; x=y; y=temp; }
int main ()
{
int m=22, n=33;
string s1="C++", s2="Forum";
swap<int>(m,n);
swap<string>(s1,s2);
cout<<m<<" "<<n<<endl;
cout<<s2<<" "<<s1<<endl;
return 0;
}
Either call your function something other than swap or give it it's own namespace.

You're probably conflicting with std::swap.

Or get rid of using namespace std; and only include that parts of the standard namespace that you need.
Last edited on
When you use the unqualified function name then it conflicts with names introduced by means of the directive

using namespace std;

because there is a function with name swap in this namespace.

So that your program will work specify the qualified name of swap. Also it is a good idea to include header <string>

So the correct code will look the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
 
using namespace std;
 
template <class T>
void swap(T&x, T&y)
{ T temp=x; x=y; y=temp; }

int main ()
{
   int m=22, n=33;
   string s1="C++", s2="Forum";

   ::swap<int>(m,n);
   ::swap<string>(s1,s2);

   cout<<m<<" "<<n<<endl;
   cout<<s2<<" "<<s1<<endl;

   return 0;
}
Last edited on
Thanks a lot !! :)
Topic archived. No new replies allowed.