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

标签 c++ templates stl

<分区>

我想使用模板交换两个数字,但为什么要这样 swap(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;
}

最佳答案

#include <iostream>
using namespace std;

iostream必须包括 algorithm而且,由于您决定包括整个 std文件中的命名空间,则与 std::swap 发生冲突.删除 using namespace std;

编辑:正如@chris 在评论中指出的那样,std::swap已移至 <utility>在 C++11 中。

关于c++ - 为什么这个交换函数调用不明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20554231/

相关文章:

c++ - 如何在 C++ 中进行柯里化(Currying)?

c++ - 对容器中所有元素的成员函数结果求和的最佳方法是什么?

c++ - 在编译时确定参数的唯一性

c++ - Visual C++ 中的二进制再现性

.net - 帮助 <WinInet.h> API 中的 InternetOpenUrl 和 InternetReadFile

c++ - 为某些模板参数发出编译错误

c++ - 在 C 中包含的内联函数中注册关键字

java - 如何在 NetBeans 7.1.1 中为日志消息创建代码模板

html - 如何在 Angular 服务中创建html模板并将其用作htmlTemplateRef?

c++ - 如何将一张 map 的内容 append 到另一张 map ?