Chapter 17. Templates

Similar documents
" Templates for Functions. ! Templates for Data Abstraction. "Syntax for Class Templates. ! This swap algorithm only works for int values:

Chapter 16. Templates. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Developed By : Mrs. K. M. Sanghavi

Functions. Arash Rafiey. September 26, 2017

l Operators such as =, +, <, can be defined to l The function names are operator followed by the l Otherwise they are like normal member functions:

! Operators such as =, +, <, can be defined to. ! The function names are operator followed by the. ! Otherwise they are like normal member functions:

Introduction to Programming Using Java (98-388)

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Lecture 7. Log into Linux New documents posted to course webpage

Chapter 4 Defining Classes I

Inheritance and Overloading. Week 11

Chapter 9. Pointers and Dynamic Arrays

A pointer variable has a pointer type, and holds pointer values. If a variable uses a number of adjacent locations, the address of the

Absolute C++ Walter Savitch

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Problem Solving with C++

Intermediate Programming

Intermediate Programming & Design (C++) Classes in C++

Semantics of C++ Hauptseminar im Wintersemester 2009/10 Templates

COEN244: Class & function templates

TEMPLATE IN C++ Function Templates

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

eingebetteter Systeme

7 TEMPLATES AND STL. 7.1 Function Templates

Reminder: compiling & linking

Chapter Contents. An Introduction to Sorting. Selection Sort. Selection Sort. Selection Sort. Iterative Selection Sort. Chapter 9

Sahaj Computer Solutions OOPS WITH C++

Assertions, pre/postconditions

Basic Templates Intro

Lesson 13 - Vectors Dynamic Data Storage

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

SFU CMPT Topic: Class Templates

Review of Important Topics in CS1600. Functions Arrays C-strings

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

C++ For Science and Engineering Lecture 15

Introduction to Programming

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

class Array; // Class template declaration class Array public: // T="type",e.g.,int or float Array(int n); // Create array of n elements Array(); // C

Polymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types.

Pointers and Dynamic Arrays

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

Exercise 1.1 Hello world

CPSC 427: Object-Oriented Programming

III. Classes (Chap. 3)

Templating functions. Comp Sci 1570 Introduction to C++ Administrative notes. Review. Templates. Compiler processing. Functions Overloading

Variables. Data Types.

Function Overloading

CMSC202 Computer Science II for Majors

Programming in C++ 4. The lexical basis of C++

Object Oriented Design

S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Assignment 1: grid. Due November 20, 11:59 PM Introduction

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

C:\Temp\Templates. Download This PDF From The Web Site

Informatica 3 Syntax and Semantics

I/O Streams. Stream Input. I/O Stream Manipulators. State-of-Stream Member Functions. I/O Stream Format Flag Member Functions

Protection Levels and Constructors The 'const' Keyword

Cpt S 122 Data Structures. Templates

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Suppose that the following is from a correct C++ program:

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

And Even More and More C++ Fundamentals of Computer Science

Compilation/linking revisited. Memory and C/C++ modules. Layout of C/C++ programs. A sample C program demo.c. A possible structure of demo.

Memory and C/C++ modules

ADTs & Classes. An introduction

Introduction to C++ Systems Programming

Week 8: Operator overloading

Exceptions, Templates, and the STL

CSE 1223: Introduction to Computer Programming in Java Chapter 6 Arrays

2 2

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

AMCAT Automata Coding Sample Questions And Answers

Object Oriented Programming. Solved MCQs - Part 2

Programming in C++: Assignment Week 8

Lecture-5. Miscellaneous topics Templates. W3101: Programming Languages C++ Ramana Isukapalli

TEMPLATES AND EXCEPTION HANDLING

Object Oriented Design

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays

Creating a C++ Program

Test 2: CPS Owen Astrachan. November 17, Name: Honor code acknowledgement (signature)

CS201 Some Important Definitions

Pointers & Dynamic Arrays

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Instantiation of Template class

Chapter 3 Function Overloading

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Object-Oriented Principles and Practice / C++

EECS402 Lecture 02. Functions. Function Prototype

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Largest Online Community of VU Students

Chapter void Test( int, int, int ); // Function prototype int main() // Function heading { int h; // Local variable

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

C++ Important Questions with Answers

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Transcription:

Chapter 17 Templates

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

17.1 Templates for Algorithm Abstraction 3

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; } 4

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; } 5

A General swap_values A generalized version of swap_values is shown here. 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 6

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

Template Details template<class T> is the template prefix Tells compiler that the declaration or definition that follows is a template 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 8

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 9

Templates and Declarations A function template may also have a separate declaration The template prefix and type parameter are used 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 A file included with #include is, in most cases, equivalent to being "in the same file" 10

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 <class VariableType> void swap_values(variabletype& v1, VariableType& v2) { VariableType temp; } 11

12

Templates with Multiple Parameters Function templates may use more than one parameter Example: template<class T1, class T2> All parameters must be used in the template function 13

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 14

Program Example: A Generic Sorting Function The sort function below uses an algorithm that does not depend on the 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 15

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 following. 16

17

18

19

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 20

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 21

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 This code would not work, because the assignment operator used in swap_values does not work with arrays: int a[10], b[10]; <code to fill the arrays> swap_values(a, b); 22

17.2 Templates for Data Abstraction 23

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<class T> 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 24

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

Template Class Pair (cont.) 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; }; 26

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 Example: To declare an object so it can hold a pair of integers: Pair<int> score; or for a pair of characters: Pair<char> seats; 27

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'); 28

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 29

Defining a Pair Constructor This is a definition of the constructor for class Pair that takes two arguments template<class T> Pair<T>::Pair(T first_value, T second_value) : first(first_value), second(second_value) { //No body needed due to initialization above } The class name includes <T> 30

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

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>: int add_up(const Pair<int>& the_pair); //Returns the sum of two integers in the_pair 32

Template Functions with Template Class Parameters Function add_up from a previous example can be made more general as a template function: template<class T> T add_up(const Pair<T>& the_pair) //Precondition: operator + is defined for T //Returns sum of the two values in the_pair 33

Program Example: An Array Class The example in the following displays is a class template whose objects are lists The lists can be lists of any type The interface is found in Display 17.4 (1-2) The program is in Display 17.5 The implementation is in Display 17.6 (1-3) 34

35

36

37

38

39

40

41

typedef and Templates You specialize a class template by giving a type argument to the class name such as Pair<int> The specialized name, Pair<int>, 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<Type_Arg> New_Type_Name; For example: typedef Pair<int> PairOfInt; PairOfInt pair1, pair2; 42