Copyright 2006 Pearson Addison-Wesley, 2008, 2009 Joey Paquet 9-1 Concordia University Department of Computer Science and Software Engineering COMP345.

Slides:



Advertisements
Similar presentations
Copyright © 2002 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 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.
Generics and the ArrayList Class
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 17 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 
Stacks and Queues. Sample PMT online… Browse 1120/sumII05/PMT/2004_1/
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Computer Science II Exam I Review Monday, February 6, 2006.
 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.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Templates and the STL.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
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.
Data Structures Using C++ 2E
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Templates Templates for Algorithm Abstraction. Slide Templates for Algorithm Abstraction Function definitions often use application specific adaptations.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
 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.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Learning Objective  Standard Template Library.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
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 –
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
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.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
C++ Template.
C++ Templates.
Motivation and Overview
Exceptions, Templates, and the Standard Template Library (STL)
ADT Implementations: Templates and Standard Containers
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
Constructors and Other Tools
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
Presentation transcript:

Copyright 2006 Pearson Addison-Wesley, 2008, 2009 Joey Paquet 9-1 Concordia University Department of Computer Science and Software Engineering COMP345 – Advanced Program Design with C++ Lecture 10: Templates

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-2 Learning Objectives  Function Templates  Class Templates  Vectors  Iterators

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-3 Introduction  C++ templates  Allow very "general" definitions for functions and classes  Type names are "parameters" instead of actual types  Precise definition determined at run-time

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-4 Function Templates  Typical function swapValues: void swapValues(int& var1, int& var2) { int temp; temp = var1; var1 = var2; var2 = temp; }  Applies only to variables of type int  But code would work for any types!

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-5 Function Templates vs. Overloading  Could overload function for char’s: void swapValues(char& var1, char& var2) { char temp; temp = var1; var1 = var2; var2 = temp; }  But notice: code is nearly identical!  Only difference is type used in 3 places

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-6 Function Template Syntax  Allow "swap values" of any type variables: template void swapValues(T& var1, T& var2) { T temp; temp = var1; var1 = var2; var2 = temp; }  First line called "template prefix"  Tells compiler what’s coming is "template"  And that T is a type parameter

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-7 Template Prefix  Recall: template  In this usage, "class" means "type", or "classification"  Can be confused with other "known" use of word "class"!  C++ allows keyword typename in place of keyword class here  But most use class anyway

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-8 Template Prefix  Again: template  T can be replaced by any type  Predefined or user-defined (like a C++ class type)  In function definition body:  T used like any other type  Note: can use other than T, but T is "traditional" usage

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-9 Function Template Definition  swapValues() function template is actually large "collection" of definitions!  A definition for each possible type!  Compiler only generates definitions when required  But it’s "as if" you’d defined for all types  Write one definition  works for all types that might be needed

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-10 Calling a Function Template  Consider following call: swapValues(int1, int2);  C++ compiler "generates" function definition for two int parameters using template  Likewise for all other types  Needn’t do anything "special" in call  Required definition automatically generated

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-11 //Program to demonstrate a function template. #include using std::cout; using std::endl; //Interchanges the values of variable1 and variable2. //The assignment operator must work for the type T. template void swapValues(T& variable1, T& variable2) { T temp; temp = variable1; variable1 = variable2; variable2 = temp; } int main( ) { int integer1 = 1, integer2 = 2; cout << "Original integer values are " << integer1 << " " << integer2 << endl; swapValues(integer1, integer2); cout << "Swapped integer values are " << integer1 << " " << integer2 << endl; char symbol1 = 'A', symbol2 = 'B'; cout << "Original character values are: " << symbol1 << " " << symbol2 << endl; swapValues(symbol1, symbol2); cout << "Swapped character values are: " << symbol1 << " " << symbol2 << endl; return 0; } Calling a Function Template

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-12 Compiler Complications  Function declarations and definitions  Typically we have them separate  For templates  not supported on most compilers!  Safest to place template function definition in file where invoked  Many compilers require it appear 1 st  Often we #include all template definitions

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-13 More Compiler Complications  Check your compiler’s specific requirements  Some need to set special options  Some require special order of arrangement of template definitions vs. other file items  Most usable template program layout:  Template definition in same file it’s used  Ensure template definition precedes all uses  Can #include it

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-14 Multiple Type Parameters  Can have: template  Not typical  Usually only need one "replaceable" type  Cannot have "unused" template parameters  Each must be "used" in definition  Error otherwise!

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-15 Algorithm Abstraction  Refers to implementing templates  Express algorithms in "general" way:  Algorithm applies to variables of any type  Ignore incidental detail  Concentrate on substantive parts of algorithm  Function templates are one way C++ supports algorithm abstraction

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-16 Defining Templates Strategies  Develop function normally  Using actual data types  Completely debug "ordinary" function  Then convert to template  Replace type names with type parameter as needed  Advantages:  Easier to solve "concrete" case  Deal with algorithm, not template syntax

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-17 Inappropriate Types in Templates  Can use any type in template for which code makes "sense"  Code must behave in appropriate way  e.g., swapValues() template function  Cannot use type for which assignment operator isn’t defined  Example: an array: int a[10], b[10]; swapValues(a, b);  Arrays cannot be "assigned"!

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-18 Class Templates  Can also "generalize" classes template  Can also apply to class definition  All instances of T in class definition replaced by type parameter  Just like for function templates!  Once template defined, can declare objects of the class

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-19 Class Template Definition template class Pair { public: Pair(); Pair(T firstVal, T secondVal); void setFirst(T newVal); void setSecond(T newVal); T getFirst() const; T getSecond() const; private: T first; T second; };

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-20 Template Class Pair Members template Pair ::Pair(T firstVal, T secondVal) { first = firstVal; second = secondVal; } template void Pair ::setFirst(T newVal) { first = newVal; }

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-21 Template Class Pair  Objects of class have "pair" of values of type T  Can then declare objects: Pair score; Pair seats;  Objects then used like any other objects  Example uses: score.setFirst(3); score.setSecond(0);

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-22 Pair Member Function Definitions  Notice in member function definitions that use a template parameter type:  Each definition is itself a "template"  Requires template prefix before each definition  Class name before :: is Pair  Not just " Pair "  But constructor name is just " Pair "  Destructor name is also just " ~Pair "

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-23 Class Templates as Parameters  Consider: int addUP(const Pair & the Pair);  The type ( int ) is supplied to be used for T in defining this class type parameter  It "happens" to be call-by-reference here  Again: template types can be used anywhere standard types can

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-24 Class Templates Within Function Templates  Rather than defining new overload: template T addUp(const Pair & the Pair); //Precondition: Operator + is defined for values of type T //Returns sum of two values in the Pair  Function now applies to all kinds of numbers

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-25 Restrictions on Type Parameter  Only "reasonable" types can be substituted for T  Consider:  Assignment operator must be "well-behaved"  Copy constructor must also work  If T involves pointers, then destructor must be suitable!  Similar issues as function templates

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-26 Type Definitions  Can define new "class type name"  To represent specialized class template name  Example: typedef Pair PairOfInt;  Name PairOfInt now used to declare objects of type Pair : PairOfInt pair1, pair2;  Name can also be used as parameter, or anywhere else type name allowed

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-27 Friends and Templates  Friend functions can be used with template classes  Same as with ordinary classes  Simply requires type parameter where appropriate  Very common to have friends of template classes  Especially for operator overloads (as we’ve seen)

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-28 Templates and Inheritance  Nothing new here  Derived template classes  Can derive from template or non-template class  Derived class is then naturally also a template class  Syntax same as ordinary class derived from ordinary class

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-29 Vectors  Vector Introduction  Recall: arrays are fixed size  Vectors: "arrays that grow and shrink"  During program execution  Defined in Standard Template Library(STL)  Using template class

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-30 Vector Basics  Similar to array:  Has base type  Stores collection of base type values  Declared differently:  Syntax: vector  Indicates template class  Any type can be "plugged in" to Base_Type  Produces "new" class for vectors with that type  Example declaration: vector v;

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-31 Vector Use  #include using namespace std;  Vector template class is defined in the vector library in namespace std  vector v;  declares an empty vector of integers named v. In order to initialize a vector, one has to rely on the constructor :  vector v(10);  declares a vector of 10 integers, all initialized to 0. Note that if one wants to create an initialized vector of values of a user-defined type, such as in:  vector v(10);  then the default constructor for MyClass must properly (allocate and) initialize the data members of the class.

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-32 Vector Use  The elements of the vector are referred to using the standard square brackets array notation:  v[i]  The square brackets notation can be used to refer to existing elements, but cannot be used to initialize new elements. In order to add new elements after initialization:  vector v; v.push_back(42);  Once an element has been initialized either through declaration or through the push_back() method, it can be assigned other values using the square bracket notation.  The vector class template also provides a size() method that returns the number of elements in the vector. That crucial information allows you (for example) to loop through a vector:  for(int i = 0; i < v.size(); i++) cout << v[i] << endl;  Note that using the square brackets notation to refer to an element out of the initialized bounds of the vector will result in erratic program behavior, as with dereferencing wild pointers (which it is, in fact, due to the internal pointer implementation of vector).

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-33 Vector Use  You can use the overloaded = (assignment) operator to assign one vector to another, for example  v1 = v2  so long as they are vectors of the same type (e.g. both vector or vector ). In this case the contents of v1 are overwritten with the contents of v2 and v1 is truncated or extended to be the same length as v2.  You might also consider using the at() function in preference to the square brackets.  v.at(92)  is the same as  v[92]  except that it will terminate the program if v[92] does not exist, whereas v[92] will result in erratic program behavior.

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-34 Vector Example: Display 7.7 Using a Vector (1 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-35 Vector Example: Display 7.7 Using a Vector (2 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-36 Two-dimensional vectors  A two-dimensional vector in C++ is just a vector of vectors. For example, you could define a two-dimensional vector of integers as follows:  vector > v2;  Note the space between and the second >. If you have them next to each other, as in >>,the compiler interprets it as an operator and flags it as an error. This definition gives you an empty two-dimensional vector. If you wanted to grow it with push_back(), you would have to push back a one-dimensional vector, not a single int. For example:  vector v(5); v2.push_back(v);  To initialize a two-dimensional vector to be of a certain size, you first have to initialize a one- dimensional vector and then use this to initialize the two-dimensional one:  vector v(5); vector > v2(8,v);  You can picture v2 as a two-dimensional vector consisting of eight rows with five integers in each row. You may refer to individual elements of a two-dimensional vector by using two subscripts; the following sets the third element of the fifth row of v2 to 99:  v2[4][2] = 99; // first element of the first row is v2[0][0]  The following procedure would display a two-dimensional vector of int :  void display (const vector >& vy) { for (int i = 0; i < vy.size(); i++) { for (int j = 0; j < vy[i].size(); j++) cout << vy[i][j] << " "; cout << endl; } }

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-37 Vectors: pitfalls  a vector's well behavior depends on the well- behaved definition of the vector's base type  Constructors, assignment, copy  The square bracket notation on vectors does not perform boundary checking  The at() member function does  As much as possible, vectors should be passed as references  Avoid proliferation of vectors, as they are memory- consumptive

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-38 Other containers as template classes  list : doubly-linked list  slist : single-linked list  deque : double-ended queue  Adapter template classes from deque  queue : single-ended queue (LILO)  stack : LIFO stack  map : functional associative container  set : aggregation without repetition

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-39 Iterators  Each of the STL container classes has its own type of iterator.  An iterator is a construct that allows you to cycle through the data items stored in a container class  Generalization of a pointer

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-40 Iterators  Uniform use across container classes  ++, -- : moving to the next/previous element  ==, != : testing if two iterators are pointing to the same element or not  * (dereferencing) : allowing to access the data “pointed to” by the iterator  c.begin() : returns an iterator that points to the first element of the container c  c.end() : returns an iterator that corresponds to the end-marker of the container c (i.e. after the last element)

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-41 Display 19.1 Iterators Used with a Vector (1 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-42 Display 19.1 Iterators Used with a Vector (2 of 2)

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-43 Kinds of Iterators  Different containers have different access behavior  Forward-only (only ++ )  Bidirectional ( ++ and -- )  Random access ( ++, --, [] )  When using a constant iterator, its dereferenced element is constant, i.e. cannot be assigned a new value  Reverse iterators allow to iterate from c.end() to c.begin(), referred to as c.rbegin() and c.rend()  Problem: c.end() is a sentinel, not a regular iterator, it cannot be incremented/decremented

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-44 Forward/reverse iterators //Program to demonstrate a reverse iterator. #include using std::cout; using std::endl; using std::vector; using std::vector ::iterator; using std::vector ::reverse_iterator; int main( ) { vector container; container.push_back('A'); container.push_back('B'); container.push_back('C'); cout << "Forward:\n"; iterator p; for (p = container.begin( ); p != container.end( ); p++) cout << *p << " "; cout << endl; cout << "Reverse:\n"; reverse_iterator rp; for (rp = container.rbegin( ); rp != container.rend( ); rp++) cout << *rp << " "; cout << endl; return 0; }

Iterator class : example template class Node { public: Node(T theData, Node * theLink) : data(theData), link(theLink){} Node * getLink( ) const { return link; } const T getData( ) const { return data; } void setData(const T& theData) { data = theData; } void setLink(Node * pointer) { link = pointer; } private: T data; Node *link; }; Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-45

Iterator class : example template class ListIterator { public: ListIterator( ) : current(NULL) {} ListIterator(Node * initial) : current(initial) {} const T operator *( ) const { return current->getData( ); ListIterator operator ++( ) //Prefix form { current = current->getLink( ); return *this; } bool operator ==(const ListIterator& rightSide) const { return (current == rightSide.current); } private: Node *current; }; #endif //ITERATOR_H Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-46

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-47 Drawbacks to templates  Many compilers have poor support for templates, or use differing syntax (e.g. iterators), so the use of templates can make code less portable.  Most compilers produce confusing error messages when errors are detected in template code, due to the fact that the executed code is generated by the compiler and does not appear in the original code. This can make templates difficult to develop and fix.  Each use of a template may cause the compiler to generate extra code (an instantiation of the template), so the indiscriminate use of templates can lead to code bloat, resulting in excessively large executables.  Separate compilation of template definitions and template function declarations is not yet implemented in most compilers, resulting in the programmer having to place template function definitions in the same file where the template function is invoked. This can be solved by putting the template definition in an implementation file and #include it in any other implementation file that uses this template. This solution is an exception to the general rules governing the use of header files and program files in separate compilation.

Copyright 2006 Pearson Addison-Wesley, 2008 Joey Paquet 9-48 Summary  Function templates  Define functions with parameter for a type  Class templates  Define class with parameter for subparts of class  Predefined vector and basic_string classes are template classes  Many container template classes are available, along with various iterators