0

When I compile this code I get an error saying

call of overloaded swap(int&, int&) is ambiguous

but I've written only one swap function here.

Can you tell me why the function was ambiguous and what changes I need to do to run the program correctly?

using namespace std;

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

int main()
{
    int a, b;

    cout << "Enter two elements: ";

    cin >> a;
    cin >> b;

    swap(a, b);
    cout << "a is "<<a << '\t'<<"b is " << b << std::endl;

    return 0;
}

Why was the swapping function overloaded even though it has only only swap function?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
praveen
  • 53
  • 1
  • 1
  • 4
  • You are "using namespace std", which gives you access to std:swap, and that is giving ambiguity to your own swap function. – Muscles Apr 20 '13 at 02:34
  • It seems you're learning C++. Please stop adding `using namespace std;` in your code. It is a [terrible practice](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c) and the extra bit of typing it takes to qualify things with `std::` is well worth it. – Praetorian Apr 20 '13 at 02:54
  • The code as given should work, but will fail as soon as you include part of the standard library. – pmr Apr 20 '13 at 02:55

2 Answers2

3

You should use

 ::swap(a,b); //use one in global namespace, which is the one you defined

if you would like to call the one you defined. Since std has also defined a swap function template, the compiler will search for std namespace if you do not use ::.

More specifically, the parameter a and b are of type int, which is defined in std namespace, when compiler searches for swap, it will find both versions: the one in std namespace and the other you defined in global namespace. You need to tell compiler which one it should use explicitly, otherwise, it will lead to ambiguity.

taocp
  • 23,276
  • 10
  • 49
  • 62
2

Because you have "using namespace std;", and presumably you are including "algorithm", you have visibility of std::swap. This gives you the ambiguity that the compiler is warning you about.

The solution is either not to add "using namespace std;", or to call your own function in the unnamed namespace explicitly, by calling it as "::swap(a, b)"

Muscles
  • 471
  • 4
  • 12