Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<string>
- template <typename T>
- void swap(T a , T b)
- {
- T temp = a;
- a = b;
- b = temp;
- std::cout<<"Myswap"<<std::endl;
- }
- template <typename T1>
- void swap1(T1 a , T1 b)
- {
- T1 temp = a;
- a = b;
- b = temp;
- std::cout<<"Myswap1"<<std::endl;
- }
- int main()
- {
- int a = 10 , b = 20;
- std::string first = "hi" , last = "Bye";
- swap(a,b);
- std::cout<<"a = "<<a<<" b = "<<b<<std::endl;
- std::cout<<"------------------"<<std::endl;
- swap(first, last);
- std::cout<<"first = "<<first<<" last = "<<last<<std::endl;
- std::cout<<"------------------"<<std::endl;
- int c = 50 , d = 100;
- std::string name = "abc" , surname = "def";
- swap1(c,d);
- std::cout<<"c = "<<c<<" d = "<<d<<std::endl;
- std::cout<<"------------------"<<std::endl;
- swap1(name,surname);
- std::cout<<"name = "<<name<<" surname = "<<surname<<std::endl;
- std::cout<<"------------------"<<std::endl;
- swap(c,d);
- std::cout<<"c = "<<c<<" d = "<<d<<std::endl;
- std::cout<<"------------------"<<std::endl;
- swap(name,surname);
- std::cout<<"name = "<<name<<" surname = "<<surname<<std::endl;
- std::cout<<"------------------"<<std::endl;
- return 0;
- }
- /*
- https://stackoverflow.com/questions/61325323/trying-to-use-templatised-fuctions-to-swap-two-strings
- Output:
- Myswap
- a = 10 b = 20
- ------------------
- first = Bye last = hi
- ------------------
- Myswap1
- c = 50 d = 100
- ------------------
- Myswap1
- name = abc surname = def
- ------------------
- Myswap
- c = 50 d = 100
- ------------------
- name = def surname = abc
- ------------------
- 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