Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
20 views
6 pages
Template Function
Uploaded by
mughees ahmad
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
Download
Save
Save Template Function For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
20 views
6 pages
Template Function
Uploaded by
mughees ahmad
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
Carousel Previous
Carousel Next
Download
Save
Save Template Function For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 6
Search
Fullscreen
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
You might also like
Unit 4 CPP
PDF
100% (1)
Unit 4 CPP
71 pages
Generic Programming: by Rohan Kalra
PDF
No ratings yet
Generic Programming: by Rohan Kalra
22 pages
KMS Sir Slides
PDF
No ratings yet
KMS Sir Slides
238 pages
Templates and Intro To The Standard Template Library (Vectors)
PDF
No ratings yet
Templates and Intro To The Standard Template Library (Vectors)
73 pages
Lec12. Templates
PDF
No ratings yet
Lec12. Templates
13 pages
Programming in C and C++ - Unit V
PDF
100% (1)
Programming in C and C++ - Unit V
27 pages
Templates in c
PDF
100% (1)
Templates in c
11 pages
OODP-Unit_4 (1)
PDF
No ratings yet
OODP-Unit_4 (1)
108 pages
Unit 5
PDF
100% (1)
Unit 5
25 pages
Chapter 4 - The C++ Standard Template Library (STL)
PDF
No ratings yet
Chapter 4 - The C++ Standard Template Library (STL)
70 pages
Chapter 1, Unit - IV (Templates)
PDF
100% (1)
Chapter 1, Unit - IV (Templates)
13 pages
SE - Lecture 03-30 (OOP in C++)
PDF
No ratings yet
SE - Lecture 03-30 (OOP in C++)
217 pages
C++ Templates: Characteristics of Generic Libraries
PDF
100% (1)
C++ Templates: Characteristics of Generic Libraries
18 pages
CS - 1004 - Week-13 - Introduction To Templates - Hassan
PDF
No ratings yet
CS - 1004 - Week-13 - Introduction To Templates - Hassan
34 pages
Oop Lect7
PDF
No ratings yet
Oop Lect7
46 pages
06 Templates
PDF
No ratings yet
06 Templates
59 pages
OOP 5
PDF
No ratings yet
OOP 5
39 pages
21CSC101T Oodp Unit-4
PDF
No ratings yet
21CSC101T Oodp Unit-4
105 pages
Templates Generic Programming
PDF
No ratings yet
Templates Generic Programming
23 pages
unit5oops
PDF
No ratings yet
unit5oops
23 pages
CS101L Manual 7
PDF
No ratings yet
CS101L Manual 7
14 pages
chtp8_15P2
PDF
No ratings yet
chtp8_15P2
28 pages
OODP unit 4
PDF
No ratings yet
OODP unit 4
21 pages
Unit 4 Oodp
PDF
No ratings yet
Unit 4 Oodp
97 pages
Overloads and templates
PDF
No ratings yet
Overloads and templates
8 pages
Classes-Template in C++
PDF
No ratings yet
Classes-Template in C++
15 pages
Unit V Template
PDF
No ratings yet
Unit V Template
33 pages
Generic Programming STL
PDF
100% (1)
Generic Programming STL
23 pages
Oops Unit 5
PDF
No ratings yet
Oops Unit 5
57 pages
RJ OOP unit 5
PDF
No ratings yet
RJ OOP unit 5
7 pages
Template and Namespace
PDF
No ratings yet
Template and Namespace
30 pages
Templates in C (1)
PDF
No ratings yet
Templates in C (1)
26 pages
Notes Exception & Templates
PDF
No ratings yet
Notes Exception & Templates
9 pages
templates
PDF
No ratings yet
templates
21 pages
Templates_in_C
PDF
No ratings yet
Templates_in_C
26 pages
PPT11 Templates
PDF
No ratings yet
PPT11 Templates
40 pages
Templates
PDF
No ratings yet
Templates
35 pages
OOPS6
PDF
No ratings yet
OOPS6
33 pages
OOPs with C--_CSE2001_Unit 4 - Exception and Template.pptx
PDF
No ratings yet
OOPs with C--_CSE2001_Unit 4 - Exception and Template.pptx
32 pages
OODP Unit 4
PDF
No ratings yet
OODP Unit 4
21 pages
Templates
PDF
No ratings yet
Templates
22 pages
Templates in C
PDF
No ratings yet
Templates in C
26 pages
UNIT 03 - Lecture 27 - Templates
PDF
No ratings yet
UNIT 03 - Lecture 27 - Templates
25 pages
Object-Oriented Programming: Template
PDF
No ratings yet
Object-Oriented Programming: Template
29 pages
Introduction To C++ Templates and Exceptions
PDF
No ratings yet
Introduction To C++ Templates and Exceptions
23 pages
Master C++ 10
PDF
No ratings yet
Master C++ 10
23 pages
Unit V_OOP
PDF
No ratings yet
Unit V_OOP
45 pages
OODP Unit 4
PDF
No ratings yet
OODP Unit 4
21 pages
Templates in C++
PDF
No ratings yet
Templates in C++
26 pages
Templates
PDF
No ratings yet
Templates
17 pages
CH8_
PDF
No ratings yet
CH8_
18 pages
TemplatesNotes
PDF
No ratings yet
TemplatesNotes
8 pages
LECTURE 11
PDF
No ratings yet
LECTURE 11
15 pages
WINSEM2023-24 ICSE102L TH VL2023240503410 2024-05-02 Reference-Material-I
PDF
No ratings yet
WINSEM2023-24 ICSE102L TH VL2023240503410 2024-05-02 Reference-Material-I
20 pages
Lab Answers
PDF
No ratings yet
Lab Answers
4 pages
4444
PDF
No ratings yet
4444
5 pages
Introduction to Templates
PDF
No ratings yet
Introduction to Templates
2 pages
C++ Templates Notes
PDF
No ratings yet
C++ Templates Notes
26 pages