24.2 Templates: The Hard Way

I l @ ve RuBoard

Suppose we want to define a function max to return the maximum of two items. Actually, we don't want to define just one max function, but a family of functions: one to find the maximum of two int s, one for float s, one for char s, and so on.

We start by defining a parameterized macro to generate the code for the function. This is called the definition stage . The macro looks like this:

 #define define_max(type) type max(type d1, type d2) { \     if (d1 > d2)                                      \         return (d1);                                  \     return (d2);                                      \ } 

Each line except the last one ends in a backslash ( \ ). A #define macro spans a single line, so the backslash turns our five lines into one. By putting the backslashes in the same column, we can easily tell if we miss one.

This macro generates no code. It merely provides the definition that is used in the next phase to generate the functions we want. This is called the generation phase. The following three statements use the define_max macro to generate three versions of the max function:

 define_max(int); define_max(float); define_max(char); 

Finally, somewhere in the code we use the functions we've just defined. (This is called the use phase , of course.)

 int main(  ) {     float f = max(3.5, 8.7);     int   i = max(100, 800);     char ch = max('A', 'Q'); 

Figure 24-1 shows the source code for the #define style templates and the code generated by them.

Figure 24-1. Code generated by #define style templates
figs/c++2_2401.gif

This method works adequately for simple functions like max . It doesn't work well for larger functions. One drawback to this system is that we must invoke the macro define_max for each data type we want to use. It would be nice if C++ called define_max automatically.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net