1

I wanted to swap two number using a template but why does this swap(x, y); give an error as an ambiguous call.

#include <iostream>
using namespace std;

template <class T>

void swap(T &a, T &b) {
    T temp = a;
    a = b;
    b = temp;
}

int main () {
    int x = 14;
    int y = 7;
    swap(x, y);
    cout << x << y;
}
suspectus
  • 15,729
  • 8
  • 46
  • 54
Chiran
  • 183
  • 1
  • 4
  • 14

1 Answers1

6
#include <iostream>
using namespace std;

iostream must be including algorithm and, since you decided to include the entire std namespace in your file, you have a collision with std::swap. Remove using namespace std;

EDIT: As @chris points out in the comments, std::swap was moved to <utility> in C++11.

Ed S.
  • 119,398
  • 20
  • 176
  • 254