Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter6 LISTS AND STRINGS. Outline 1. List Specifications 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Simply Linked.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
Chapter 14: Overloading and Templates
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
 2006 Pearson Education, Inc. All rights reserved Templates.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
Chapter 8 Arrays and Strings
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Templates Zhen Jiang West Chester University
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Chapter Nine: Subprograms Lesson 09. What are they  Modularized code  Might return a value  Functions  Or not  Procedures  Subroutines  In object.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Learners Support Publications Classes and Objects.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Computer Engineering Rabie A. Ramadan Lecture 5.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Templates Class Templates Used to specify generic class types where class members data types can be specified as parameters, e.g. here is a generic List.
March 2006 Copyright, 2006 Oxford Consulting, Ltd C++ Templates Templates F Part of the ongoing development of the C++ language F Integral part.
CS212: Object Oriented Analysis and Design
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
 Templates enable us to define generic classes and functions and thus provides support for generic programming. Generic types are used as parameters.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Templates Where the TYPE is generic. Templates for functions Used when the you want to perform the same operation on different data types. The definition.
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
 2006 Pearson Education, Inc. All rights reserved Templates.
Chapter 7: User-Defined Functions II
Standard Template Library
C++ Templates.
Introduction to C++ Systems Programming.
Introduction to Custom Templates
CS212: Object Oriented Analysis and Design
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Classes and Objects.
Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Submitted By : Veenu Saini Lecturer (IT)
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Corresponds with Chapter 5
Presentation transcript:

Chapter 7 Templates

Objectives Introduction Function Templates Class Templates Standard Template Library

Introduction Templates is a facility provided by the C++ language to write a common function that is independent of a data type but which embodies the common algorithm and that the C++ language on its own creates the actual function as and when the need arises. Advantages: ease in code development and ease in code maintenance. The programmer can create a template with some or all variables therein having unspecified data types. Whenever the template is invoked by passing arguments of a certain type, the C++ language on its own replaces the unspecified type with the type of the arguments passed. Such templates can be created for individual functions as well as entire classes. Templates are used for creating family of classes or functions. Example of templates is given for the swap function in Examples 1 and 2.

Introduction Example 1: Swapping two integers void swap_values(int & v1, int & v2) { int temp; temp = v1; v1 = v2; v2= temp; } Example 2: Swapping two characters void swap_values(char & v1, char & v2) { char temp; temp = v1; v1 = v2; v2 = temp; }

Function Templates The syntax for creating a template for a generic function is given below: The template definition begins with the template keyword. This is followed by a list of generic data types in angular brackets. Each generic type is prefixed with the class keyword and, if the template function works on more than one generic type, commas separate them. Thereafter, the function template is defined just like an ordinary function. The return type comes first. This is followed by the name of the function, which in turn is followed by a pair of parentheses enclosing the list of formal arguments the function takes.

Function Templates However, there should be at least one formal argument of each one of the generic types mentioned within the angular brackets. As an example, consider the template for the function swap. template void swap(T& v1, T& v2) { T temp; temp = v1; v1 = v2; v2 = temp; } Type parameter Example 3: Template for function swap()

Function Templates When the function swap is called by passing two integers, the compiler generates an actual definition for the function by replacing each occurrence of T by the keyword int. (See Example 4). Example 4 void main() { int x,y; x=5; y=10; cout<<“before swapping\n”; cout<<x<<“t”<<Y<<endl; swap(x,y); cout<<“after swapping\n”; cout<<x<<“t”<<Y<<endl; }

Function Templates Similarly, if the function swap is called by passing two floats, the compiler generates an actual definition for the function by replacing each occurrence of T by the keyword float. (See Example 5). Example 5 void main() { float x,y; x=5; y=10; cout<<“before swapping\n”; cout<<x<<“t”<<Y<<endl; swap(x,y); cout<<“after swapping\n”; cout<<x<<“t”<<Y<<endl; }

Function Templates Objects of classes can also be passed to the function swap. The compiler will generate an actual definition by replacing each occurrence of T by the name of the corresponding class. (See Example 6). Example 6 void main() { distance d1(4,7.5), d2(5,9.5) cout<<“before swapping\n”; cout<<d1.feet<<“t”<<d1.inch<<endl; swap(d1,d2); cout<<d1.feet<<“t”<<d1.inch<<endl; } Advantages of templates: It implements code reusability thus saving a lot of effort in code development.

Function Templates The compiler generates an actual function from a template only once for a given data type. Subsequent calls with the same data type will not generate the definition again. This is because the compiler first looks for an exact match to resolve a function call before looking for a template. If it finds an exact match, it does not look for a template. Since the first function call itself generates the function definition, subsequent calls do not do so. The entire definition of the function must appear in the header file. Otherwise, the compiler would not be able to generate the correct definition while compiling a user program in which the function template has been called.

Function Templates It is sometimes necessary to override the function template by an actual function.(See Example 7). Example 7 : Template for larger function template T& larger(const T& v1, const T& v2) { return a>b? a:b; } This works for variables of ordinary data types, however, it does not work correctly if strings are passed to it. (See Example 8). Example 8 : Calling the larger function by passing strings char *s1 = “abcd”, *s2=“mnop”; char *s3=larger (s1,s2); This is because only the addresses of the two strings and not their contents are compared by the larger function.

Function Templates For the character strings to execute, a special version of the function larger could be defined along with the template. (See Example 9). Example 9 : Overriding the template for the function larger char * larger (char *a, char *b) { return strcmp(a,b)> 0 ? a:b; } If the function larger is called by passing two strings, the function in Listing Example 8 will be called while the template will be ignored.

Function Templates Function templates can be overloaded. (See Example 10). Templates can be overloaded either by using template functions or ordinary functions. In that case, compiler looks for exact match in ordinary function first, if it is not matching then it looks for template function having exact match. An error will be generated if there is no match Example 10: template void disp (const T &a) { for (int i=1; i<=20; i++) cout<<a; } template void disp (const T &a, const int no) //overloaded version of disp() { for (int i=1; i<=no; i++) cout<<a; cout<<endl; }

Function Templates Function template can be used to sort an elements (See Example 11). Example 11: Template for bubble sort template void bubble_sort(Item data[ ], int n) { int i, j; Item temp; for(i = 0; i < n-1 ; i++) { for(j= 0; j< n-i-1 ; j++) { if(data[j] > data[j+1]) { temp = data[j]; data[j] = data[j+1]; data[j+1] = temp; }

Function Templates More than one generic type also be mentioned in the template definition. Example 12: template void disp (T1 x, T2 y) { cout<<“displaying:”<<“x=“<<x<<“\ty=“<<y; }

Class Templates The need for class templates stems from the frequent need for generic classes (Queue, Stack, Array, etc.) that handle data of different types. Consider the set of two classes whose member functions have similar definitions, the mere difference being the type of the private data members upon whom they operate: Example 11: Classes with similar definitions class Integer { int i; public : void f1(const int &); void f2(const int &); //rest of the class }; class Character { char i; public : void f1(const char &); void f2(const char &); //rest of the class };

Class Templates The presence of two or more different classes that are different only in the data type of the data members upon whom their member functions work creates huge difficulties in code maintenance. Any change in one of the classes will have to be replicated in all of the others. This situation certainly demands the creation of a template class. (See Example 14). Example 14 template class X {T val; public: void f1(const T &); void f2(const T &); //rest of the class };

The definition of the template class begins with the keyword template. This is followed by the list of type and non-type template arguments enclosed in angular brackets. Type template arguments are those that represent a data type. An actual built-in or user-defined type replaces them when an object is declared. Each type template argument is preceded by the keyword class. Non-type template arguments are variables of built-in or user-defined type. Actual constant values are passed for these non-type template arguments. The data type precedes each non-type template argument. Thereafter, the class is defined using the usual syntax. Class Templates

Member functions of a template class are defined in the same way as the template class itself. (See Example 15). Example 15 The definition begins with the template keyword. This is followed by the list of type and non-type template arguments enclosed in angular brackets. Each type template argument is preceded by the keyword class; each non-type template argument is preceded by its data type.

Class Templates Thereafter, the function is defined using the usual syntax except for one important difference. The class name given before the scope resolution operator is followed by the names of all template arguments enclosed in angular brackets. Objects of this template class can be declared as follows: X intObj; While declaring the object, the class name is followed by the type and non-type template parameter(s) enclosed in angular brackets. This is followed as usual by the name of the object itself. When the compiler sees the declaration of the object, it replaces each occurrence of the template argument by the template parameter in the definition of the class template and generates a separate class. In the preceding case, each occurrence of the token T in the class X will be replaced by the keyword int. Objects of template classes, once declared, can be used just like any other object.

Class Templates The compiler generates the exact definition of a class from a given class template once only for each data type. Member functions of class templates are defined in the header files themselves. Features of Class Templates: 1.A template class can take more than one template type argument. (Example 16). Example 16: template class X { T val1; S val2; public: //rest of the class };

Class Templates Features of Class Templates(contd…): 2.A template class can take a non-type template argument. (See Example 17). Example 17: template class X { T val1; //rest of the class }; Objects of this template class can be declared as follows: X intObj;

Class Templates

Features of Class Templates(contd…): 3. The name of the template argument cannot be used more than once in the template class’s list of template arguments. (See Example 18). Example 18: template //Error class X {//rest of the class };

Class Templates Features of Class Templates(contd…): 4. The same name for a template argument can be used in the list of template arguments of two different template classes. (Example 10.19). Example 19 template class X {//rest of the class }; template class Y {//rest of the class };

Class Templates Features of Class Templates(contd…): 5. The name of a template argument need not be the same in the declaration and the definition of the template class. (See Example 20). Example 20 template class X; //declaration template //ok, different name for the //template argument in the definition class X //definition {//rest of the class };

Class Templates 6. Formal arguments of template functions can be objects of a template class. (See Example 21). Example 21: template class X {//rest of the class }; template void f1(X v) { //definition }

Class Templates Nested Class Templates: Nested classes can be created for template classes in the same way as they are created for non-template classes. Example 22. Example 22: template class A { class B { T x; //rest of the class B }; //definition of class A };

Class Templates Implementing Stack in C++ using Class Template #include using namespace std; template class stack{ T* arr; static int top; public: stack(int); void push(T); T pop(); bool empty(); }; template int stack ::top = -1; template stack ::stack(int x){ this->arr = new T(x); }

Class Templates template void stack ::push(T a){ this->arr[++top] = a; } template T stack ::pop(){ T a = this->arr[top--]; return a; } template bool stack ::empty(){ return (top==-1); } void main(){ stack s(10); int i; for(i=0;i<10;i++){ s.push(i); } while(!s.empty()){ cout<<s.pop()<<endl; } }

Standard Template Library The standard implementation of C++ provide a set of header files where a large number of useful class templates have been defined. These files contain definitions of the class templates, their member functions, and a number of global associated functions. The global associated functions implement commonly used algorithms. This library of class templates and their helper global functions is known as the Standard Template Library (STL). The following is a list of commonly used member functions and the associated global functions:

Standard Template Library The list class The list class is used to create sequential containers. Elements of the list are single objects. (See page 383). For using the list template class, the header file list needs to be included in the source code: #include The elements of a list occupy a non-contiguous memory. They are doubly linked through a pair of pointers. One of the pointers points at the next element and the other points at the previous element of the list. This allows both forward and backward traversal. The number of elements a list object would have can be specified at the time of declaration. (See page 383). A default value can be specified for these elements. (See page 383). A list can be created from an existing array. (See page 383).