Why does this work?!

So I made a mistake while typing my code:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
using namespace std;

template <typename T> //or "class T"
void display(T x, T y, int n=1);

template <typename T> 
void swap(T x, T y);

int main()
{
	int a = 10, b = 20;
	double x = 50, y = 1000;

	display(a, b);
	swap(a, b);
	display(a, b);

	display(x, y, 2);
	swap(x, y);
	display(x, y, 5);

	while (cin.get() == '\n')
		continue;
}

template <typename T>
void display(T x, T y, int n)
{
	if (n == 1)
		cout << "a = " << x
		<< "\nb = " << y << "\n\n";
	else
		cout << "x = " << x
		<< "\ny = " << y << "\n\n";
}

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


To my amazement..... it worked! Why does "swap()" work when the arguements are all copied values, not references (as I intended)?
Last edited on
The cpp.sh-sites compiler stops on error:
16:11: error: call of overloaded 'swap(int&, int&)' is ambiguous

16:11: note: candidates are:
void swap(T, T) [with T = int]
void std::swap(_Tp&, _Tp&) [with _Tp = int]

In other words that compiler sees both your swap and std::swap. It is quite likely that your compiler does too (but avoids the ambiguity somehow).

Remove the using namespace std; and add
1
2
using std::cin;
using std::cout;


Then you should not have the std::swap visible any more.
Neither MSVC or GCC (MinGW version) compile the code due to the ambiguity.

MSVC
error C2668: 'swap' : ambiguous call to overloaded function

GCC
error: call of overloaded 'swap(int&, int&)' is ambiguous

So out of interest, what compiler are you using?

Andy
Last edited on
I found the error. Don't worry, you guys didn't have a shot.

I unintentionally crippled your efforts. :(

I originally mistyped the code like this:

1
2
3
4
5
6
7
8
template <typename T>
void swap(T x, T y, int n)
{
	T temp;
	temp = x;
	x = y;
	y = temp;
}


I think that the third argument was not only making the function unique enough to not be considered ambiguous, but was also causing my function call to call std::swap instead; that's why my code seemed to work.

I fixed my error before posting this.. Thinking that I was doing the forum a favor by removing an unrelated error... And also saving some embarrassment lol

Thanks guys. I had no idea about std::swap.. This helped a lot.
Last edited on
Topic archived. No new replies allowed.