c++ - 为什么对模板化函数有模棱两可的调用?
问题描述
我在 C++ 中创建模板时遇到问题。我正在为 mac 使用 xcode。
将 an 传递int
给swap
函数时,我得到错误代码“模糊调用”。但是,传递string
s 工作正常。这是为什么?
这是我的代码
#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::string
s调用是有效的。那是因为for有一个专业化。专业化被认为是更好的匹配,所以它被称为而不是你自己的。std::swap
std::string
swap
推荐阅读
- javascript - Sinon - 返回不是函数
- python - 当 acc_no = 2 时,我正在尝试打印特定列
- sas - 在 do 循环迭代 SAS 中创建变量
- python - 如何使以序列作为输入的函数的返回类型取决于该序列类型?
- excel - 使用快递网站的 VBA 进行网页抓取
- python - 熊猫多索引数据框中的小时和分钟平均值
- python - 根据第一个唯一列值提取表
- eclipse - 在 C/C++ 的 Eclipse IDE 中,什么键命令选择当前单词?
- php - 当有人从一个帐户登录另一个用户时自动注销用户
- mysql - SQLSTATE[HY000] [1045] 用户'wymtavvh_admin'@'localhost'的访问被拒绝(使用密码:YES)