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); \ }
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 templatesThis 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 |