24.3 Templates: The C Way

I l @ ve RuBoard

24.3 Templates: The C++ Way

Templates allow you to define a generic function. C++ then uses this template to generate a specific instance of the function as needed. For example, to define the function max as a template, we write:

 template<typename kind> kind max(kind d1, kind d2) {     if (d1 > d2)                                             return (d1);                                     return (d2);                                     } 

The construct <typename kind> tells C++ that the word kind can be replaced by any type.

This template declaration corresponds to the definition of the parameterized macro. Like the parameterized macro, it generates no code; it merely provides a definition for the next phase.

Now we can use the template much like we used the functions defined by the parameterized macro:

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

You may have noticed that we skipped the generation phase. That's because C++ automatically performs the generation for us. In other words, C++ looks at the line:

 float f = max(3.5, 8.7); 

and sees that it uses the function max (float, float) . It then checks to see whether the code for this function has been generated and generates it if necessary. In other words, everything is automatic. (There are practical limits to what can be done automatically, as you will see in the implementation details section.)

Figure 24-2 shows the code generated by the template implementation of max . From this you can see that the first time max is used for a float it generates the floating-point version of max . Next we use max for int, and the int version of max is created. Note that the last line:

 int  i2 = max(600, 200); 

does not generate any function. This is because we've already generated the integer version max and don't need to do so again.

Figure 24-2. Template code generation
figs/c++2_2402.gif
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