gpt4 book ai didi

c++ - 尝试使用模板函数交换两个字符串

转载 作者:行者123 更新时间:2023-12-01 12:17:31 25 4
gpt4 key购买 nike

#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实现中添加打印件,您会注意到,它是而不是std::string,而仅是int的。

与您的版本相比,首选std::swap,因为存在std::basic_string类型的explicit specialization。如果不存在,则通话可能会模棱两可。
对于int,在查找过程中不考虑 namespace std,因此您的版本是唯一可接受的版本。

Also can you tell me that how are stl strings passed as arguements by default i.e are they passed by value or by reference?



C++中的所有内容均按值传递,除非您将其明确标记为按引用传递。

关于c++ - 尝试使用模板函数交换两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61325323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com