c++ - 尝试使用模板化函数交换两个字符串
问题描述
#include<iostream>
#include<string>
template <typename T>
void swap(T a , T b)
{
T temp = a;
a = b;
b = temp;
}
template <typename T1>
void swap1(T1 a , T1 b)
{
T1 temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10 , b = 20;
std::string first = "hi" , last = "Bye";
swap(a,b);
swap(first, last);
std::cout<<"a = "<<a<<" b = "<<b<<std::endl;
std::cout<<"first = "<<first<<" last = "<<last<<std::endl;
int c = 50 , d = 100;
std::string name = "abc" , surname = "def";
swap1(c,d);
swap1(name,surname);
std::cout<<"c = "<<c<<" d = "<<d<<std::endl;
std::cout<<"name = "<<name<<" surname = "<<surname<<std::endl;
swap(c,d);
swap(name,surname);
std::cout<<"c = "<<c<<" d = "<<d<<std::endl;
std::cout<<"name = "<<name<<" surname = "<<surname<<std::endl;
return 0;
}
**Output**
a = 10 b = 20
first = Bye last = hi
c = 50 d = 100
name = abc surname = def
c = 50 d = 100
name = def surname = abc
两者基本上都具有相同的函数定义,那么为什么实际上只swap()
交换字符串,而没有呢?swap1()
swap()
swap1()
您还可以告诉我,stl 字符串是如何默认作为参数传递的,即它们是通过值传递还是通过引用传递?
解决方案
我明白为什么人们现在对 ADL 皱眉头了……
您看到的是Argument Dependent Lookup的效果。如果你在你的swap
实现中添加一个 print ,你会注意到它没有被调用 for std::string
,只是 for int
。
std::swap
比您的版本更受欢迎,因为存在类型的明确专业化std::basic_string
。如果它不存在,调用可能会模棱两可。
对于int
,std
在查找过程中不考虑命名空间,因此您的版本是唯一可以接受的。
您还可以告诉我,stl 字符串是如何默认作为参数传递的,即它们是通过值传递还是通过引用传递?
C++ 中的所有内容都是按值传递的,除非您明确将其标记为按引用传递。
推荐阅读
- django - POSTMAN Curd 基于类的视图
- python - Python平衡分区问题,返回子组之间的最小总和被忽略的测试用例
- python - 如何使用 sqlalchemy 在 Python 运行时打印出 TLS 版本?
- javascript - 使用 socket.io 和 React 获取数据的正确方法是什么?
- loops - 如何在 for 循环的每次迭代中保存变量
- c++ - 是否使用对使用 reinterpret_cast 未定义行为强制转换的指针的引用?
- python - 蟒蛇 | Flask Url_For MissingSchema:无效的 URL 错误
- angular - 有没有办法自动更新和构建一个android应用程序
- hibernate - jBPM在计时器事件后创建重复任务:多个实例正在运行
- python - 通过 dj_rest_auth 在用户注册中保存额外的字段