为什么对模板化函数的调用不明确?
我在 C++ 中创建模板时遇到问题。我正在为 mac 使用 xcode。
将 an 传递int给swap函数时,我收到错误代码“模棱两可的调用”。但是,传递strings 工作正常。这是为什么?
这是我的代码
#include <iostream>
#include <cmath>
using namespace std;
template <typename T>
void swap(T& c, T& d)
{
T temp = c;
c = d;
d = temp;
}
int main()
{
int a = 10;
int b = 20;
swap(a, b); // this is an error "ambiguous call"
cout << a << "t" << b;
string first_name = "Bob";
string last_name = "Hoskins";
swap(first_name, last_name); // this works
cout << first_name << "t" << last_name;
return 0;
}
回答
你有using namespace std;这带来std::swap了范围。这意味着swap您编写的模板与 冲突std::swap,当您传递 2 个整数时,您会得到一个模棱两可的调用。
外卖:从不做using namespace std;
有趣的部分是swap用 2 std::strings调用是有效的。那是因为有一个专门的std::swapfor std::string。专业化被认为是更好的匹配,因此它被称为而不是您自己的swap.