[ fromfile: templates.xml id: functiontemplates ]
Function templates create type-checked functions that all work on the same pattern.
Example 11.1. src/templates/template-demo.cpp
[ . . . . ] template <class T> T power (T a, int exp) { T ans = a; while (--exp > 0) { ans *= a; } return (ans); }
Example 11.2. src/templates/template-demo.cpp
Each time the compiler sees a template function used for the first time with a specific combination of parameter types, we say the template is instantiated.
Subsequent uses of of power(Complex, int)
or power(Fraction, int)
translate into ordinary function calls.
Note | |
---|---|
One important difference between overloaded functions and multiple specializations of the same template function is that overloaded functions must return the same type. Example 11.2 shows different versions of the template |
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |