试图使用模板化功能交换两个字符串

问题描述 投票:4回答:2
#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字符串如何作为参数传递,即它们是按值还是按引用传递?

c++ templates pass-by-reference pass-by-value stdstring
2个回答
3
投票

我知道为什么人们现在不喜欢ADL ...

© www.soinside.com 2019 - 2024. All rights reserved.