Guest User

Modified code and question

a guest
Apr 20th, 2020
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include<iostream>
  2. #include<string>
  3.  
  4. template <typename T>
  5. void swap(T a , T b)
  6. {
  7.     T temp = a;
  8.     a = b;
  9.     b = temp;
  10.     std::cout<<"Myswap"<<std::endl;
  11. }  
  12.  
  13. template <typename T1>
  14. void swap1(T1 a , T1 b)
  15. {
  16.     T1 temp = a;
  17.     a = b;
  18.     b = temp;
  19.     std::cout<<"Myswap1"<<std::endl;
  20. }
  21.  
  22.  
  23. int main()
  24. {
  25.     int a = 10 , b = 20;
  26.     std::string first = "hi" , last = "Bye";
  27.    
  28.     swap(a,b);
  29.     std::cout<<"a = "<<a<<" b = "<<b<<std::endl;
  30.     std::cout<<"------------------"<<std::endl;
  31.    
  32.     swap(first, last);  
  33.     std::cout<<"first = "<<first<<" last = "<<last<<std::endl; 
  34.     std::cout<<"------------------"<<std::endl;
  35.    
  36.     int c = 50 , d = 100;
  37.     std::string name = "abc" , surname = "def";
  38.  
  39.     swap1(c,d);
  40.     std::cout<<"c = "<<c<<" d = "<<d<<std::endl;
  41.     std::cout<<"------------------"<<std::endl;
  42.    
  43.     swap1(name,surname);
  44.     std::cout<<"name = "<<name<<" surname = "<<surname<<std::endl; 
  45.     std::cout<<"------------------"<<std::endl;
  46.    
  47.    
  48.     swap(c,d);
  49.     std::cout<<"c = "<<c<<" d = "<<d<<std::endl;
  50.     std::cout<<"------------------"<<std::endl;
  51.    
  52.     swap(name,surname);
  53.     std::cout<<"name = "<<name<<" surname = "<<surname<<std::endl; 
  54.     std::cout<<"------------------"<<std::endl;
  55.    
  56. return 0;
  57. }
  58. /*
  59. https://stackoverflow.com/questions/61325323/trying-to-use-templatised-fuctions-to-swap-two-strings
  60.  
  61. Output:
  62.  
  63. Myswap
  64. a = 10 b = 20
  65. ------------------
  66. first = Bye last = hi
  67. ------------------
  68. Myswap1
  69. c = 50 d = 100
  70. ------------------
  71. Myswap1
  72. name = abc surname = def
  73. ------------------
  74. Myswap
  75. c = 50 d = 100
  76. ------------------
  77. name = def surname = abc
  78. ------------------
  79.  
  80. Apparently it looks like swap1(name,surname); is called. But this is the only time it is called. Why is this the case?
Add Comment
Please, Sign In to add comment