Function Template

◀ Recursive Function Versus Non-recursive Function▶ Generality in Functions
Amazon Having discussed class templates in Chapter 3.4 you should have some idea how function templates work. A function template,or a generic class, accepts multiple data types of the arguments. For example if a function template accepts one argument, the data type of the argument can be int, short, char, struct, and even a class!

A classic example of a function template is to swap the values of the two given arguments. Here it is:
template <class Any>  /* <typename Any> is a newer usage */
void swaps(Any &a, Any &b){ Any temp; temp = a; a = b; b = temp; }
You probably wonder if this function works with only rudimentary types such as short, int, and char. The way to test it is simple: you replace Any with a type and see if it works. For example, let’s say tt is a struct and t and t2 are its objects. Do you think we can do the following?
tt temp;
temp = t;
t = t2;
t2 = temp;
Of course we can. What about a class object? Suppose I have a class named Score and its two objects named score and score2. Do the following statements work?

Score temp;
temp = score;
score = score2;
score2 = temp;
The assignment operator between two objects of the same class performs a member-to-member copy by default. So the statements above DO work. You can have a pointer to char as one of the class data members and see if swaps() works.

Pointers often give us surprises, so don’t take everything for granted without experimentation!
◀ Recursive Function Versus Non-recursive Function▶ Generality in Functions

fShare
Questions? Let me know!