我有一个用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
纳入范围。这意味着您编写的模板swap
与std::swap
冲突,并且当您向它传递2个int时,您会得到一个模糊调用。
导读:从不dousing namespace std;
有趣的是,用2个std::string
s调用swap
是有效的。这是因为std::swap
对std::string
有专门化。专门化被认为是更好的匹配,因此它被称为而不是您自己的swap
。