首页 > 解决方案 > 尝试使用模板化函数交换两个字符串

问题描述

#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++templatespass-by-referencepass-by-valuestdstring

解决方案


我明白为什么人们现在对 ADL 皱眉头了……

您看到的是Argument Dependent Lookup的效果。如果你在你的swap实现中添加一个 print ,你会注意到它没有被调用 for std::string,只是 for int

std::swap比您的版本更受欢迎,因为存在类型的明确专业化std::basic_string。如果它不存在,调用可能会模棱两可。
对于int,std在查找过程中不考虑命名空间,因此您的版本是唯一可以接受的。

您还可以告诉我,stl 字符串是如何默认作为参数传递的,即它们是通过值传递还是通过引用传递?

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


推荐阅读