1: //swap2.cpp
2: //Illustrates a Swap template function.
4: #include <iostream>
5: #include <string>
6: using namespace std;
9: template<typename T> //Note use of "typename" rather than "class"
10: void Swap
11: (
12: T& first, //inout
13: T& second //inout
14: )
15: /**<
16: Swaps the values in two variables.
17: @pre <em>first</em> and <em>second</em> have been initialized.
18: @post The values in <em>first</em> and <em>second</em have
19: been interchanged.
20: */
21: {
22: T temp = first;
23: first = second;
24: second = temp;
25: }
28: int main()
29: {
30: int a = 7, b = 9;
31: double x = 2.3, y = 7.4;
32: string firstName = "John", lastName = "Henry";
34: cout << "\na is " << a << " and b is " << b << ".\n";
35: Swap(a, b);
36: cout << "Now a is " << a << " and b is " << b << ".\n\n";
38: cout << "x is " << x << " and y is " << y << ".\n";
39: Swap(x, y);
40: cout << "Now x is " << x << " and y is " << y << ".\n\n";
42: cout << "firstName is " << firstName
43: << " and lastName is " << lastName << ".\n";
44: Swap(firstName, lastName);
45: cout << "Now firstName is " << firstName
46: << " and lastName is " << lastName << ".\n\n";
48: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
49: }
50: