why the following function template does not work

Anybody know why the following compile error occurs?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

template <typename Any>
void swap(Any & a, Any & b);

int main()
{
	int a = 3;
	int b = 5;
	swap(a, b);
	cout << a << " " << b << endl;
	
	return 0;
}

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


cplusprimer.cpp: In function `int main()':
cplusprimer.cpp:12: error: call of overloaded `swap(int&, int&)' is ambiguous
cplusprimer.cpp:6: note: candidates are: void swap(Any&, Any&) [with Any = int]
/usr/include/c++/3.4/bits/stl_algobase.h:126: note:                 void std::swap(_Tp&, _Tp&) [with _Tp = int]
Because the STL also contains a function called swap that takes the same arguments, and because you have using namespace std;, you have those 2 functions in basically the same namespace (the global one).

Either remove using namespace std; or rename your function.
Thanks, it works.
Topic archived. No new replies allowed.