为什么这个交换函数调用不明确?

Chi*_*ran 1 c++ templates stl

我想用模板交换两个数字,但为什么这个交换(x,y); 作为一个模棱两可的电话给出错误.

#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;
}
Run Code Online (Sandbox Code Playgroud)

Ed *_* S. 6

#include <iostream>
using namespace std;
Run Code Online (Sandbox Code Playgroud)

iostream必须包括,algorithm并且,因为您决定std在文件中包含整个命名空间,所以您与之发生冲突std::swap.去掉using namespace std;

编辑:正如@chris在评论中指出的那样,std::swap被转移到<utility>C++ 11中.