Copyright © 2008 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 16 Templates. Learning Objectives Function Templates – Syntax, defining – Compiler complications Class Templates – Syntax – Example: Pair class.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates.
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.
1 Templates Chapter What You Will Learn Using function templates to created a group of overloaded functions Using class templates to create a group.
Generics and the ArrayList Class
Template Classes. A class that depends on an underlying data type(s) likewise can be implemented as a template class. We can have a ‘NewClass’ of ints,
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1 ; Programmer-Defined Functions Two components of a function definition.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12A Separate Compilation and Namespaces For classes this time.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Stacks and Queues. Sample PMT online… Browse 1120/sumII05/PMT/2004_1/
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 5 Functions for All Subtasks.
Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 1 Overview – Chapter Section 4 Arrays and Classes (10.4)
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’
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, 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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Functions for All Subtasks.
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.
Chapter 13 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Recursive Functions for Tasks(13.1) Recursive Functions.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 14 Recursion.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
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.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 7 Arrays.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
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 2006 Pearson Addison-Wesley, 2008, 2009 Joey Paquet 9-1 Concordia University Department of Computer Science and Software Engineering COMP345.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
Chapter 1 C++ Templates (Sections 1.6, 1.7). Templates Type-independent patterns that can work with multiple data types. Function Templates  These define.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
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 © 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 –
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 5 Functions for All Subtasks.
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 © 2006 Pearson Addison-Wesley. All rights reserved Today’s Learning Objectives  Function Templates  Recursion Functions.
C++ Template.
Programming with ANSI C ++
Chapter 5 Functions for All Subtasks 1
Chapter 5 Functions for All Subtasks 1
10.2 Classes Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Templates.
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
Friends, Overloaded Operators, and Arrays in Classes
Arrays Lecture 11.
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
Presentation transcript:

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

Slide Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction

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

Slide Templates for Algorithm Abstraction Function definitions often use application specific adaptations of more general algorithms For example: 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; } For example: 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 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; } void swap_values(char& v1, char& v2) { char temp; temp = v1; v1 = v2; v2 = temp; }

Now We Want to Swap Integers Up until now, we would have to write a new function or at least swap char to nt.. Up until now, we would have to write a new function or at least swap char to nt.. void swap_values(int& v1, int& v2) { int temp; temp = v1; v1 = v2; v2 = temp; } void swap_values(int& v1, int& v2) { int temp; temp = v1; v1 = v2; v2 = temp; } Why do all this rewriting? Why do all this rewriting?

Slide A General swap_values It would be nicer to write one function that could be used for any type A generalized version of swap_values might be void swap_values(type_of_var& v1, type_of_var& v2) { type_of_var temp; temp = v1; v1 = v2; v2 = temp; } void swap_values(type_of_var& v1, type_of_var& v2) { type_of_var temp; temp = v1; v1 = v2; v2 = temp; } This function, if type_of_var could accept any type, could be used to swap values of any type This function, if type_of_var could accept any type, could be used to swap values of any type

Slide A C++ function template will allow swap_values to swap values of two variables of the same type Example: template void swap_values(T& v1, T& v2) { T temp; temp = v1; v1 = v2; v = temp; } Example: template void swap_values(T& v1, T& v2) { T temp; temp = v1; v1 = v2; v = temp; } Template prefix Template parameter Templates for Functions

Slide Template Details template is the template prefix Tells compiler that the declaration or definition that follows is a template Tells compiler that the declaration or definition that follows is a template Tells compiler that T is a type parameter Tells compiler that T is a type parameter class means type in this context (typename could replace class but class is usually used) 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

Slide 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; // for the char version Example: To call the template version of swap_values char s1, s2; // for the char version int i1, i2; // for the int version int i1, i2; // for the int version … swap_values(s1, s2); swap_values(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 Templates and Declarations A function template may also have a separate declaration The template prefix and type parameter are used The template prefix and type parameter are used Depending on your compiler Depending on your compiler 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 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 or.h file with implementation code

Slide T is the traditional name for the type parameter Any valid, non-keyword, identifier can be used Any valid, non-keyword, identifier can be used "VariableType" could be used template void swap_values(VariableType& v1, VariableType& v2) { VariableType temp; … } "VariableType" could be used template void swap_values(VariableType& v1, VariableType& v2) { VariableType temp; … } The Type Parameter T

Slide

Slide Templates with Multiple Parameters Function templates may use more than one parameter Example: template Example: template All parameters must be used in the template function

Slide 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 This allows us to concentrate on the substantive part of the algorithm

Slide Program Example: A Generic Sorting Function The sort function defined in the next uses an algorithm that does not depend on the base type of the array sort uses two helper functions index_of_smallest also uses a general algorithm and could be defined with a template index_of_smallest also uses a general algorithm and could be defined with a template swap_values has already been adapted as a template swap_values has already been adapted as a template

A Generic Algorithm 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, index++) { index_of_next_smallest = index_of_smallest(a, index, number_used); swap_values(a[index], number_used); swap_values(a[index], a[index_of_next_smallest]); }} a[index_of_next_smallest]); }} The same algorithm could be used to sort an array of any type The same algorithm could be used to sort an array of any type

All three functions, defined with templates in C++, are demonstrated in next 3 slides

Slide

Slide

Slide

Slide 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 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 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 Defining Templates When defining a template it is a good idea… To start with an ordinary function that accomplishes the task with one type 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 Then debug the ordinary function Next convert the function to a template by replacing type names with a type parameter Next convert the function to a template by replacing type names with a type parameter

Slide Inappropriate Types for Templates Templates can be used for any type for which the code in the function makes sense swap_values swaps individual objects of a type swap_values swaps individual objects of a type However, this code would not work, because the assignment operator used in swap_values does not work with arrays: int a[10], b[10]; swap_values(a, b); However, this code would not work, because the assignment operator used in swap_values does not work with arrays: int a[10], b[10]; swap_values(a, b);

Slide Section 17.1 Conclusion Can you Identify a template prefix? Identify a template prefix? Identify a parameter type in a template prefix? Identify a parameter type in a template prefix? Compare and contrast function overloading with the use of templates? Compare and contrast function overloading with the use of templates? What additional complexities are involved when class types are involved as parameter types?

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

Slide 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 The syntax for class templates is basically the same as for function templates template comes before the template definition Type parameter T is used in the class definition just like any other type Type parameter T can represent any type

Slide A Class Template The following is a class template An object of this class contains a pair of values of type T An object of this class contains a pair of values of type T template class Pair { public: Pair( ); Pair( T first_value, T second_value); … continued on next slide template class Pair { public: Pair( ); Pair( T first_value, T second_value); … continued on next slide

Slide Template Class Pair (cont.) void set_element( int position, T value); //Precondition: position is 1 or 2 //Postcondition: position indicated is set to value void set_element( int position, T value); //Precondition: position is 1 or 2 //Postcondition: position indicated is set to value T get_element( int position) const; // Precondition: position is 1 or 2 // Returns value in position indicated private: T first; T second; }; T get_element( int position) const; // Precondition: position is 1 or 2 // Returns value in position indicated private: T first; T second; };

Slide Declaring Template Class Objects Once the class template is defined, objects may be declared Declarations must indicate what type is to be used for T Declarations must indicate what type is to be used for T Example: To declare an object so it can hold a pair of integers: Pair score; Example: To declare an object so it can hold a pair of integers: Pair score; or for a pair of characters: Pair seats; or for a pair of characters: Pair seats;

Slide Using the Objects After the 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'); Continuing the previous example: score.set_element(1,3); score.set_element(2,0); seats.set_element(1, 'A');

Slide Defining the Member Functions Member functions of a template class are definedthe same way as member functions of ordinary classes The only difference is that the member function definitions are themselves templates The only difference is that the member function definitions are themselves templates

Slide 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 } second(second_value) { //No body needed due to initialization above } The class name includes The class name includes Defining a Pair Constructor

Slide Defining set_element Here is a definition for set_element in the template class Pair void Pair ::set_element(int position, T value) { if (position = = 1) first = value; else if (position = = 2) second = value; else … }

Slide Template Class Names as Parameters The name of a template class may be used as the type of a function parameter Example: To create a parameter of type Pair : int add_up( const Pair & the_pair); //Returns the sum of two integers in the_pair Example: To create a parameter of type Pair : int add_up( const Pair & the_pair); //Returns the sum of two integers in the_pair

Slide 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 // for T //Returns sum of the two values in // the_pair // the_pair

Slide The example in the following displays is a class template whose objects are lists The lists can be lists of any type The lists can be lists of any type The interface is found in the next two slides. The program is in the two slides after those. The implementation is in the next three slides. Program Example: An Array Class

Slide

Slide

Slide

Slide

Slide

Slide

Slide

Slide typedef and Templates You specialize a class template by giving a type argument to the class name such as Pair 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 The specialized name, Pair, is used just like any class name

typedef and Templates 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; typedef Pair PairOfInt; PairOfInt pair1, pair2;

Slide 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 member function get_element for the class template Pair? Give the definition for the constructor with zero arguments for the template class Pair? Give the definition for the constructor with zero arguments for the template class Pair?

Slide Chapter End