为什么对模板化函数有歧义调用?

  • 本文关键字:函数 歧义 调用 c++
  • 更新时间 :
  • 英文 :


我有一个用c++创建模板的问题。我在mac上使用xcode。

int传递给swap函数时,我得到错误码&;ambiguous call&;。然而,通过string的作品很好。为什么呢?

这是我的代码

#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纳入范围。这意味着您编写的模板swapstd::swap冲突,并且当您向它传递2个int时,您会得到一个模糊调用。

导读:从不dousing namespace std;

有趣的是,用2个std::strings调用swap是有效的。这是因为std::swapstd::string有专门化。专门化被认为是更好的匹配,因此它被称为而不是您自己的swap