...
main() {
int i = 10, j = 20;
myswap(i, j); // after call want i to hold 20, j to hold 10
...
}
void myswap(int& num1, int& num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
To have it work for any types, the int needs to be generalized.
Think of this as paramaterizing the type. It's just like parameter
variables that get passed in, but the type is passed in as opposed
to the value. Use the keyword
template and typename
as in the following example.
template < typename TheType >
void myswap(TheType& val1, TheType& val2) {
TheType temp;
temp = val1;
val1 = val2;
val2 = temp;
}
The template line is part of the function prototype line,
but it is generally formatted on two lines for readability.
Now when you swap ints, the int is passed into "TheType" identifier.
If you have more than one type to pass in, separate them with commas,
for example
template < typename TheType1, typename TheType2 >
You can also turn classes into templates and there is the
Standard Template Library (STL). Both will be discussed
briefly in CSS 342.