Concepts of Programming Languages

(Sean Pound) #1

424 Chapter 9 Subprograms


Although this process could be defined as a macro, a macro would have the
disadvantage of not operating correctly if the parameters were expressions with
side effects. For example, suppose the macro were defined as

#define max(a, b) ((a) > (b))? (a) : (b)

This definition is generic in the sense that it works for any numeric type.
However, it does not always work correctly if called with a parameter that has
a side effect, such as

max(x++, y)

which produces

((x++) > (y)? (x++) : (y))

Whenever the value of x is greater than that of y, x will be incremented
twice.
C++ template functions are instantiated implicitly either when the func-
tion is named in a call or when its address is taken with the & operator. For
example, the example template function defined would be instantiated twice
by the following code segment—once for int type parameters and once for
char type parameters:

int a, b, c;
char d, e, f;

...
c = max(a, b);
f = max(d, e);


The following is a C++ generic sort subprogram:

template <class Type>
void generic_sort(Type list[], int len) {
int top, bottom;
Type temp;
for (top = 0; top < len - 2; top++)
for (bottom = top + 1; bottom < len - 1; bottom++)
if (list[top] > list[bottom]) {
temp = list[top];
list[top] = list[bottom];
list[bottom] = temp;
} //** end of if (list[top]...
} //** end of generic_sort

The following is an example instantiation of this template function:
Free download pdf