0 ratings0% found this document useful (0 votes) 33 views6 pagesTemplate Function
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
966
Chapter 16 Exceptions, Templates, and the Standard Template Library (STL)
Program 16-6 (continued)
10
u
12
13
18
19
int main()
4
double *ptr; // Pointer to double
try
‘
ptr = new double [10000];
)
catch ( bad_alloe)
‘
cout << “Insufficient memory. \n";
>
return 0;
>
© Checkpoint
myprogramminglab www.myprogramminglab.com
16.1 What is the difference between a try block and a catch block?
16.2. What happens if an exception is thrown, but not caught?
16.3 I multiple exceptions can be thrown, how does the catch block know which
exception to catch?
16.4 After the catch block has handled the exception, where does program execution
resume?
16.5 How can an exception pass data back to the exception handler?
162) Function Templates
= CONCEPT: A function template is a “generic” function that can work with any data
type. The programmer writes the specifications of the function, but
substitutes parameters for data types. When the compiler encounters a
call to the function, it generates code to handle the specific data type(s)
used in the call.
Introduction
Overloaded functions make programming convenient because only one function name
must be remembered for a set of functions that perform similar operations. Each of the
functions, however, must still be written individually, even if they perform the same oper
ation. For example, suppose a program uses the following overloaded square function
int square( int number)
4
return number * number;
>Writing a
Function
Template
16.2 Function Templates
double square( double number)
4
return number * number;
y
‘The only differences between these two functions are the data types of their return values
and their parameters. In situations like this, it is more convenient to write a function tem-
plate than an overloaded function. Function templates allow you to write a single function
definition that works with many different data types, instead of having to write a separate
function for each data type used.
A function template is not an actual function, but a “mold” the compiler uses to generate
‘one or more functions. When writing a function template, you do not have to specify
actual types for the parameters, return value, or local variables. Instead, you use a type
Parameter to specify a generic data type. When the compiler encounters a call to the fune-
tion, it examines the data types of its arguments and generates the function code that will
work with those data types. (The generated code is known as a template function.)
Here is a function template for the square function:
template
T square( nunber)
4
return number * number;
>
‘The beginning of a function template is marked by a template prefix, which begins with
the key word template. Next is a set of angled brackets that contains one or more generic
data types used in the template. A generic data type starts with the key word class fol-
lowed by a parameter name that stands for the data type. The example just given only
uses one, which is named 7. (If there were more, they would be separated by commas.)
After this, the function definition is written as usual, except the type parameters are sub-
stituted for the actual data type names. In the example the function header reads
'T square(t number)
‘ris the type parameter, or generic data type. The header defines square as a function that
returns a value of type T and uses a parameter, nunber, which is also of type T. As men-
tioned before, the compiler examines each call to square and fills in the appropriate data
type for 2. For example, the following call uses an int argument:
nt yr, x= 4;
square x) +
y
This code will cause the compiler to generate the function
square( int number)
4
return number * nunber;
>
while the following statements
double y, £ = 6.2
y = square( £);
967968
Chapter 16 Exceptions, Templates, and the Standard Template Library (STL)
will generate the function
double square( double number)
4
return number * number;
>
Program 16-7 demonstrates how this function template is used.
Program 16-7
1 // This program uses a function template.
Hinclude
) #include
4 using namespace std;
© // Template definition for square function,
template
1 square(T number)
2
) return number * number;
ay
3 int main()
mk
int userInty // To hold integer input
1 double userDouble; // To hold double input
8 gout << setprecision(5);
29 cout << “Enter an integer and a floating-point value: ";
) gin >> usertnt >> userDouble;
21 cout << "Here are their squares
cout << square(userint) <<" and
3 << square( userDouble) << endl;
25 return 0;
Program Output with Example Input Shown in Bold
Enter an integer and a floating-point value: 124.2 [Enter]
Here are their squares: 144 and 17.64
NOTE: All type parameters defined in a function template must appear at least once in
9 the function parameter list.
Because the compiler encountered two calls to square in Program 16-7, each with a differ-
ent parameter type, it generated the code for two instances of the function: one with an
int parameter and int return type, the other with a double parameter and double
return type. This is illustrated in Figure 16-3.
Notice in Program 16-7 that the template appears before all calls to square. As with reg-
ular functions, the compiler must already know the template’s contents when it encounters16.2 Function Templates 969
Figure 16-3
Generated Function Code
(Template Function)
int aquare{ int number)
Function Template ‘
Function Calls return nunber * nusber:
,
=4n
.quare( x); ——P
template
1 square (1 nunber)
double x = 12.5, yy return number * nusber;
y= square(
:
double square{ double number)
‘
return number * aunber;
>
a call to the template function, Templates, therefore, should be placed near the top of the
program or in a header file.
NOTE: A function template is merely the specification of a function and by itself does
9 not cause memory to be used. An actual instance of the function is created in memory
when the compiler encounters a call to the template function,
Program 16-8 shows another example of a function template. The function, swapvars,
uses two references to type as parameters. The function swaps the contents of the vari-
ables referenced by the parameters.
Program 16-8
// This program demonstrates the swapVars function template.
Hinelude
void swapVars(T évarl, T évar2)
«
T temp;
temp = varl;
varl = var2;
var2 = temp;
»
int main()
4
char firstchar, secondchar; 11 Two chars
int firstrnt, secondrnt; 11 Two ints
double firstbouble, secondbouble; // Two doubles
(program continues)970
Chapter 16 Exceptions, Templates, and the Standard Template Library (STL)
Program 16-8 (continued)
»
// Get and swapVars two chars
cout << "Enter two characters: ";
cin >> firstChar >> secondChar;
swapvars( firetChar, secondchar) ;
cout << firstchar <<" * << secondchar << endl;
// Get and swapVars two ints
cout << "Enter two integer:
cia >> firstint >> secondint;
swapvars( firstInt, secondInt) ;
cout << firstInt <<" " << secondint << endl;
// Get and swapVars two doubles
cout << “Enter two floating-point numbers:
cin >> firstbouble >> secondDouble;
swapVars( firstDouble, secondDouble) ;
cout << firstDouble << * " << secondDouble << endl;
return 0;
Program Output with Example Input Shown in Bold
Enter two characters: AB [Enter]
BA
Enter two integer:
105
510 [Enter]
Enter two floating-point numbers: 1.29.6 [Enter]
9.6 1.2
Using Operators in Function Templates
The square template shown earlier uses the * operator with the nunber parameter. This
works well as long as nunber is of a primitive data type such as int, float, etc. Ifa user-
defined class object is passed to the square function, however, the class must contain code
for an overloaded * operator If not, the compiler will generate a function with an error
Always remember that a class object passed to a function template must support all the
operations the function will perform on the object. For instance, if the function performs a
comparison on the object (with >, <, ==, or another relational operator), those operators
must be overloaded by the class object.
Function Templates with Multiple Types
‘More than one generic type may be used in a function template, Each type must have its
‘own parameter, as shown in Program 16-9. This program uses a function template named
Larger. This template uses two type parameters: TL and 72. The sizes of the function
parameters, varl and var2, are compared and the function returns the number of bytes
‘occupied by the larger of the two. Because the function parameters are specified with dif
ferent types, the function generated from this template can accept two arguments of differ-
‘ent types.16.2 Function Templates
Program 16-9
// This program demonstrates a function template
// with two type parameters.
#include
using namespace std;
© template
int largest(const Tl gvarl, 72 evar2)
«
2 Af (sizeof(varl) > sizeof( var2))
0 return sizeof(varl);
1 else
2 return sizeof( var2);
5}
14
5 int main()
6 «
int i = 0;
char c=" "5
float £ = 0.0;
20° double d = 0.0;
a
22 cout << “Comparing an int and a double, the largest\n"
3 << “of the two is " << largest(i, d) <<" bytes. \n";
4
cout << "Comparing a char and a float, the largest\n"
<< "of the two is " << largest(c, £) <<" bytes. \n";
25 return 0;
oy
Program Output
Comparing an int and a double, the largest.
of the two is 8 bytes.
Comparing a char and a float, the largest
of the two is 4 bytes.
NOTE: Each type parameter declared in the template prefix must be used somewhere in
9 the template definition.
Overloading with Function Templates
Function templates may be overloaded. As with regular functions, function templates are
overloaded by having different parameter lists. For example, there are two overloaded
versions of the sum function in Program 16-10. The first version accepts two arguments,
and the second version accepts three.
971