Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates.

Slides:



Advertisements
Similar presentations
Copyright © 2003 Pearson Education, Inc. Slide 1.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 19 Standard Template Library. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Iterators Constant and mutable.
Chapter 11 Separate Compilation and Namespaces. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Separate Compilation.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 16 Templates. Learning Objectives Function Templates – Syntax, defining – Compiler complications Class Templates – Syntax – Example: Pair class.
Template. 2 Using templates, it is possible to create generic functions and classes. In a generic function or class, the type of data upon which the function.
TEMPLATES Lecture Presented By SHERY KHAN Object Orienting Programming.
Chapter 17 Templates. Generic Algorithms Algorithms in which the actions or steps are defined, but the data types of the items being manipulated are not.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 5 Functions for All Subtasks.
1 Templates Chapter What You Will Learn Using function templates to created a group of overloaded functions Using class templates to create a group.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1 ; Programmer-Defined Functions Two components of a function definition.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12A Separate Compilation and Namespaces For classes this time.
 2006 Pearson Education, Inc. All rights reserved Templates.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 1 Overview – Chapter Section 4 Arrays and Classes (10.4)
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
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.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Templates Templates for Algorithm Abstraction. Slide Templates for Algorithm Abstraction Function definitions often use application specific adaptations.
Overview of C++ Templates
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Pointers *, &, array similarities, functions, sizeof.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Chapter 9 Separate Compilation and Namespaces. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Separate Compilation (9.1)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation and Namespaces.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Separate Compilation and Namespaces.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Object Oriented Programming COP3330 / CGS5409.  Class Templates  Bitwise Operators.
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
Copyright © Curt Hill Generic Functions Separating Data Type from Logic.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
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.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
CPSC 252 Templatization Page 1 Templatization In CPSC152, we saw a class vector in which we could specify the type of values that are stored: vector intData(
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Learning Objectives  Function Templates  Recursion Functions.
Programming with ANSI C ++
Templates.
Name: Rubaisha Rajpoot
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
Polymorphism Polymorphism - Greek for “many forms”
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
Data Structures and ADTs
Presentation transcript:

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction Template Specialization Slide 17- 3

Copyright © 2014 Pearson Addison-Wesley. All rights reserved Templates for Algorithm Abstraction

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Templates for Algorithm Abstraction Function definitions often use application specific adaptations of more general algorithms The general algorithm used in swap_values could swap variables of any type: void swap_values(type_of_var& v1, type_of_var& v2) { type_of_var temp; temp = v1; v1 = v2; v2 = temp; } } Slide 17- 5

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. swap_values for char Here is a version of swap_values to swap character variables: void swap_values(char& v1, char& v2) { char temp; temp = v1; v1 = v2; v2 = temp; } Slide 17- 6

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Templates for Functions A C++ function template will allow swap_values to swap values of two variables of the same type template void swap_values(T& v1, T& v2) { T temp; temp = v1; v1 = v2; v = temp; } Slide template prefix Type parameter

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. template Details template is the template prefix Tells compiler that the declaration or definition that follows is a template Tells compiler that T is a type parameter typename means type in this context T can be replaced by any type argument (whether the type is a class or not) A template overloads the function name by replacing T with the type used in a function call Original syntax (still supported and used in the textbook) template Slide 17- 8

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Calling a template Function Calling a function defined with a template is identical to calling a normal function Example: To call the template version of swap_values char s1, s2; int i1, i2; … swap_values(s1, s2); swap_values(i1, i2); The compiler checks the argument types and generates an appropriate version of swap_values Slide 17- 9

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. templates and Declarations A function template may also have a separate declaration The template prefix and type parameter are used Depending on your compiler (!!!critically important!!!) You may, or may not, be able to separate declaration and definitions of template functions just as you do with regular functions To be safe, place template function definitions in the same file where they are used with no declaration A file included with #include is, in most cases, equivalent to being "in the same file“ This means including the.cpp file and.h files with implementation code Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. The Type Parameter T T is the traditional name for the type parameter Any valid, non-keyword, identifier can be used "VariableType" could be used template void swap_values(VariableType& v1, VariableType& v2) { VariableType temp; … } ch17\17-01.cpp Slide Display 17.1

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Templates with Multiple Parameters Function templates may use more than one parameter Example: template For this code to compile, all template parameters must be used in the template function Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Algorithm Abstraction Using a template function we can express more general algorithms in C++ Algorithm abstraction means expressing algorithms in a very general way so we can ignore incidental detail This allows us to concentrate on the substantive part of the algorithm Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Program Example: A Generic Sorting Function The sort function below uses an algorithm that does not depend on the int base type of the array void sort(int a[], int number_used) { int index_of_next_smallest; for (int index = 0; index < number_used -1; index++) { index_of_next_smallest = index_of_smallest(a, index, number_used); swap_values(a[index], a[index_of_next_smallest]); } } The same algorithm could be used to sort an array of any type Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Generic Sorting: Helping Functions sort uses two helper functions index_of_smallest also uses a general algorithm and could be defined with a template swap_values has already been adapted as a template All three functions, defined with templates, are demonstrated in ch17\sortfunc.cpp and ch17\ cpp Slide Display 17.2 Display 17.3 (1-2)

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Templates and Operators The function index_of_smallest compares items in an array using the < operator If a template function uses an operator, such as <, that operator must be defined for the types being compared If a class type has the < operator overloaded for the class, then an array of objects of the class could be sorted with function template sort Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Defining Templates When defining a template it is a good idea To start with an ordinary function that accomplishes the task with one type It is often easier to deal with a concrete case rather than the general case Then debug the ordinary function Next convert the function to a template by replacing type names with a type parameter Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Inappropriate Types for Templates Templates can only be used for a type for which the code in the function makes sense swap_values swaps individual objects of a type This code would not compile, because the assignment operator used in swap_values does not work with arrays: int a[10], b[10]; swap_values(a, b); Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Slide templates and Polymorphism Templates provide compiler time polymorphism Overloading functions also results in compiler time polymorphism Overriding virtual functions is the run time polymorphism that takes more run time resources than the first two techniques

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Section 17.1 Conclusion Can you Identify a template prefix? Identify a parameter type in a template prefix? Compare and contrast function overloading with the use of templates? What additional complexities are involved when class types are involved as parameter types? Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved Templates for Data Abstraction

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Templates for Data Abstraction Class definitions can also be made more general with templates The syntax for class templates is basically the same as for function templates template comes before the template class definition Type parameter T is used in the class definition just like any other type Type parameter T can represent any type Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. A Class template The following is a class template declaration An object of this class contains two data members of type T template class Pair { public: Pair( ); Pair(T first_value, T second_value); void set_element(int position, T value); T get_element(int position) const; private: T first; T second; }; Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Declaring template Class Objects Once the class template is defined, objects may be declared Objects declarations must indicate what type is to be used for T To declare an object so it can hold a pair of integers: Pair score; or for a pair of characters: Pair seats; Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Using the Objects After declaration, objects based on a template class are used just like any other objects Continuing the previous example: score.set_element(1,3); score.set_element(2,0); seats.set_element(1, 'A'); Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Defining the Member Functions Member functions of a template class are defined the same way as member functions of ordinary classes The only difference is that the member function definitions are themselves templates Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Defining a Pair Class Constructor This is a definition of the constructor for class Pair that takes two arguments template Pair ::Pair(T first_value, T second_value) : first(first_value), second(second_value) { //No body needed due to initialization above } The constructor definition includes Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Defining set_element Here is a definition for set_element in the template class Pair template void Pair ::set_element(int position, T value) { if (position == 1) first = value; else if (position == 2) second = value; else … } Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. template Class Names as Parameters The name of a template class may be used as the type of a function parameter To create a parameter of type Pair : int add_up(const Pair & the_pair); //Returns the sum of two integers in the_pair Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. template Functions with template Class Parameters Function add_up from a previous example can be made more general as a template function: template T add_up(const Pair & the_pair) //Precondition: operator + is defined for T //Returns sum of the two values in the_pair Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Program Example: An Array Class Next example represents a class template whose objects are lists The lists can be lists of any type The interface is found in ch17\genericlist.h The program is in ch17\17-05.cpp The implementation is in ch17\genericlist.cpp Slide Display 17.4 (1-2) Display 17.5 Display 17.6 (1-3)

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Implementation Notes Note that in ch17\genericlist.h, the class definition for GenericList, we put the implementation of the overloaded << operator in the header file itself This is common for template classes with friend operators This is because << is a friend, not a member of the class; as a result, implementation is simpler this way Slide 1- 32

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Separate implementation of overloaded friend operator We can put the implementation of << into the implementation file but there is extra work Make forward declaration with the diamond in the ch17\17-07.h file Implementation of the operator << in the ch17\17-08.cpp file Slide Display 17.7 Display 17.8

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. typedef and Templates You specialize a class template by giving a type argument to the class name such as Pair The specialized name, Pair, is used just like any class name You can define a new class type name with the same meaning as the specialized name: typedef Class_Name New_Type_Name; For example: typedef Pair PairOfInt; PairOfInt pair1, pair2; Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Slide templates Features template classes do not preserve inheritance, e.g. classes Pair and Pair are unrelated template parameters may be any type names as well as constants template class Pair { … }  MAX_VALUE can be used anywhere inside the class  To create an instance of this class Pair ascii;

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Section 17.2 Conclusion Can you Give the definition for the member function get_element for the class template Pair? Give the definition for the constructor with zero arguments for the template class Pair? Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Template Specialization

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Slide Template Specialization Features - I Sometimes it may be necessary to provide a specific template implementation for one (or some) of data types used as template parameters Solution – template specialization Template class Test has one private field of any type and one member function For the int data type we need 2 member functions. ch17\spc.cpp

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Slide Template Specialization Features – II Class template specialization declaration syntax: template <> class Test { }; A template with empty <> parameter list must precede the class template specialization name Compiler interprets this declaration as a class template specialization specialization parameter after the class template name is also required and defines the specialized template’s data type

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Slide Template Specialization Features - III Compare the syntax of standard class template and the class template specialization: template class Test { }; template <> class Test { };

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Slide Template Specialization Features - IV As with regular template classes, class template specialization does not inherit any members from the original template class Any template class specialization must explicitly define all its data fields, methods, and constructors, even those that exist in the original template class – the value data field or getValue() method

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter End Slide

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display 17.1 Slide Back Next

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display 17.2 Slide Back Next

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display 17.3 (1/2) Slide Back Next

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display 17.3 (2/2) Slide Back Next

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display 17.4 (1/2) Slide Back Next

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display 17.4 (2/2) Slide Back Next

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display /2 Slide Back Next

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display /2 Slide Back Next

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display /3 Slide Back Next 1//This is the implementation file: genericlist.cpp 2//This is the implementation of the class template named GenericList. 3//The interface for the class template GenericList is in the 4//header file genericlist.h. 5#ifndef GENERICLIST_CPP 6#define GENERICLIST_CPP 7#include 8#include 9#include "genericlist.h" //This is not needed when used as we are using this file, 10 //but the #ifndef in genericlist.h makes it safe. 11using namespace std; 12 13namespace listsavitch 14{ 15 //Uses cstdlib: 16 template 17 GenericList ::GenericList(int max) : max_length(max), 18 current_length(0) 19 { 20 item = new ItemType[max]; 21 }

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display 17.6 (2/3) Slide Back Next template 24 GenericList ::~GenericList( ) 25 { 26 delete [] item; 27 } template 30 int GenericList ::length( ) const 31 { 32 return (current_length); 33 } //Uses iostream and cstdlib: 36 template 37 void GenericList ::add(ItemType new_item) 38 { 39 if ( full( ) ) 40 { 41 cout << "Error: adding to a full list.\n"; 42 exit(1); 43 } 44 else 45 { 46 item[current_length] = new_item; 47 current_length = current_length + 1; 48 } 49 }

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display 17.6 (3/3) Slide Back Next 51 template 52 bool GenericList ::full( ) const 53 { 54 return (current_length == max_length); 55 } template 58 void GenericList ::erase( ) 59 { 60 current_length = 0; 61 } 62}//listsavitch 63#endif // GENERICLIST_CPP Notice that we have enclosed all the template 64 // definitions in #ifndef... #endif.

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display /2 Slide Back Next

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display 17.7 (2/2) Slide Back Next

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Display 17.8 Slide //This is the implementation file: genericlist.cpp 3//This is the implementation of the class template named GenericList. 4 //The interface for the class template GenericList is in the 5//header file genericlist.h. 6#ifndef GENERICLIST_CPP 7#define GENERICLIST_CPP 8#include 9#include 10#include "genericlist.h" //Not needed when used as we are using this file, 11 //but the #ifndef in genericlist.h makes it safe. 12using namespace std; 13 14namespace listsavitch 15{ 16 The rest of this file is identical to Display 17.6 except for the 17 Implementation of <<. 18 template 19 ostream& operator & the_list) 20 { 21 for (int i = 0; i < the_list.current_length; i++) 22 outs << the_list.item[i] << endl; 23 return outs; 24 } 25}//listsavitch 26#endif // GENERICLIST_CPP Notice that we have enclosed all the template 27 // definitions in #ifndef... #endif. Back Next