O'Reilly logo

C++ In a Nutshell by Ray Lischner

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Tricks with Templates

Template syntax permits recursion, selection, and computation. In other words, it is a full-fledged programming language, albeit a language that is hard to write and even harder to read. The full scope and power of programming with templates is beyond the scope of this book. This section presents some tips for starting your own exploration of this exciting field. Appendix B tells you about some interesting projects in this area.

Suppose you want to write a function to round off floating-point values to a fixed number of decimal places. You decide to write the function by multiplying by a power of 10, rounding off to an integer, and dividing by the same power of 10. You can hardcode the amount, (e.g., 100) in the routine, but you prefer to use a template, in which a template parameter specifies the number of decimal digits to retain. To avoid computing the same power of 10 every time the function is called, you decide to use template programming to compute the constant at compile time.

The ipower<> template in Example 7-14 uses recursion to compute the power of any integer raised to any nonnegative integer value. Three base cases for the recursion are defined as specializations: raising any value to the 0th power is always 1, raising 0 to any power is always 0, and raising 0 to the 0th power is undefined. (As an exercise, try to define ipower more efficiently.) Finally, the ipower<> class template is used to define the round<> function template.

Example 7-14. Computing ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required