template basics

Hi everybody, I'm a beginner in c++ and I have a problem with templates. When I compile this code in visual C++ 2008 i get an error:
error C2668: 'swap' : ambiguous call to overloaded function.

Please help, I don't know what I'm doing wrong?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

template <class T> 
void swap(T &x, T &y)
    {
	 T temp;
	 temp = x;
	 x = y;
	 y = temp;
	}

int main()
{
	int i=1,j=2;
	swap(i, j);
	cout << i << j << endl;
	cin.get();
	cin.get();
	return 0;
}
There is another function called swap in the std namespace (which actually does the exact same thing as yours), try rename your function to something else, it will work.
Isn't your call to your swap() missing the type?

 
swap<int>(i, j);


Or am I thinking in C#?
Last edited on
Thanks alot R0mai that worked, and I tried what webJose suggested and it doesn't make a difference, also works,so thanks.
@webJose
If the template type can be gathered from the function parameters then you don't have to explicitly tell the complier the type, although you can and it's sometimes necessary as in this example:

1
2
3
    float f = 0.5;
    int i = 0;
    std::max<float>(f,i); 


If you don't specify the template type than the complier can't decide to call max<int> or max<float>.
I see. I'll have to try it out in C#. Maybe it is similar. Thanks for the tip!
Topic archived. No new replies allowed.