1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| #include <iostream> #include <string> #include <cstring>
struct Dog { std::string name; int age; };
template <typename T> void swap(T&, T&);
void swap(Dog&, Dog&);
int main() { std::string a = "aaa"; std::string b = "bbb"; std::cout << a << ", " << b <<std::endl; swap(a, b); std::cout << a << ", " << b <<std::endl;
std::cout << "----------" << std::endl;
Dog dog1 = {"dog aa", 5}; Dog dog2 = {"dog bb", 7}; std::cout << dog1.name << ", " << dog1.age <<std::endl; std::cout << dog2.name << ", " << dog2.age <<std::endl; swap(dog1, dog2); std::cout << dog1.name << ", " << dog1.age <<std::endl; std::cout << dog2.name << ", " << dog2.age <<std::endl; return 0; }
void swap(Dog& a, Dog& b) { swap(a.name, b.name); }
template <typename T> void swap(T& a, T& b) { T tmp = a; a = b; b = tmp; }
|