Search code examples
c++templatespass-by-referencepass-by-valuestdstring

Trying to use templatised fuctions to swap two strings


#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

Both swap() and swap1() basically have the same function-definitions then why only swap() actually swaps the strings, while swap1() does not?

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


Solution

  • I can see why people are frowning upon ADL now...

    What you see is an effect of Argument Dependent Lookup. If you'd add a print inside your swap implementation, you'd notice that it is not called for std::string, only for int.

    std::swap is preferred over your version, because there exists an explicit specialization for std::basic_string type. If it didn't exist, call would be ambiguous probably.
    For int, namespace std is not considered in the lookup process, so your version is the only acceptable.

    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?

    Everything in C++ is passed by value, unless you mark it as pass-by-reference explicitly.