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
  • 16,548
  • 8
  • 49
  • 57
Chiran
  • 183
  • 1
  • 5
  • 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.
  • 122,712
  • 22
  • 185
  • 265