Motivation for Templates

Similar documents
Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

Class and Function Templates

A linear structure is an ordered (e.g., sequenced) arrangement of elements.

A linear structure is an ordered (e.g., sequenced) arrangement of elements.

CS201 - Introduction to Programming Glossary By

Assignment of Objects

Short Notes of CS201

Doubly-Linked Lists

Dynamic Data Structures

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Summer I Instructions:

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

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

COEN244: Class & function templates

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring Instructions:

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

Instantiation of Template class

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

CSCE 110 PROGRAMMING FUNDAMENTALS

CS 2604 Homework 1 C++ Review Summer I 2003

Function Overloading

the pointer range [first, last) into the tree

! A data type for which: ! An ADT may be implemented using various. ! Examples:

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

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

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

Lab 2: ADT Design & Implementation

CS 2604 Homework 1 Greatest Hits of C++ Summer 2000

Object Oriented Programming COP3330 / CGS5409

ICOM 4035 Data Structures. Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department

CS 2604 Homework 2 Solution for Greatest Hits of C++ Fall 2000

Introduction to C++ Systems Programming

This examination has 11 pages. Check that you have a complete paper.

pointers & references

SFU CMPT Topic: Class Templates

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

Logistics. Templates. Plan for today. Logistics. A quick intro to Templates. A quick intro to Templates. Project. Questions? Introduction to Templates

CS427 Inheritance and Virtual Functions. Linked lists. 2/27. 01Replacement.cpp link! i n t GetY ( void ) { return ( y ) ; } ;

Object-Oriented Programming

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19

Intermediate Programming, Spring 2017*

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Due Date: See Blackboard

GEA 2017, Week 4. February 21, 2017

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

ADT Sorted List Operations

SYSC 2006 Winter 2012 Linear Collections: Queues

CS197c: Programming in C++

1 Short Answer (7 Points Each)

Multiple choice questions. Answer on Scantron Form. 4 points each (100 points) Which is NOT a reasonable conclusion to this sentence:

Chapter 15 - C++ As A "Better C"

การทดลองท 8_2 Editor Buffer Array Implementation

CSC1322 Object-Oriented Programming Concepts

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

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

Definition of Stack. 5 Linked Structures. Stack ADT Operations. ADT Stack Operations. A stack is a LIFO last in, first out structure.

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

CSCE 110 PROGRAMMING FUNDAMENTALS

Fast Introduction to Object Oriented Programming and C++

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

CS32 Discussion Sec.on 1B Week 2. TA: Zhou Ren

Introducing C++ to Java Programmers

CMSC 341 Lecture 7 Lists

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

III. Classes (Chap. 3)

CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation

CS

EECE.3220: Data Structures Spring 2017

Containers: Queue and List. Jordi Cortadella and Jordi Petit Department of Computer Science

List, Stack, and Queues

Consider the program...

Propedéutico de Programación

CS 2704 Spring 2001 February 6, 2001

Object Oriented Design

Practice Problems CS2620 Advanced Programming, Spring 2003

Review for Test 1 (Chapter 1-5)

Faculty of Information and Communication Technologies

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008

Module 9. Templates & STL

Iterators. node UML diagram implementing a double linked list the need for a deep copy. nested classes for iterator function objects

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

Link-Based Implementations. Chapter 4

Classes and Objects. Class scope: - private members are only accessible by the class methods.

4/27/2014. Templates II. Warmup Write the templated Swap function. Class Templates CMSC 202

Chapter 18: Stacks And Queues

COMP 2355 Introduction to Systems Programming

Pointers, Dynamic Data, and Reference Types

Traversing Trees with Iterators

Traversing Trees with Iterators

C++ 8. Constructors and Destructors

explicit class and default definitions revision of SC22/WG21/N1582 =

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists

Overloading & Polymorphism

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:

Chapter 18: Stacks And Queues

CSCI 123 Introduction to Programming Concepts in C++

Object-Oriented Principles and Practice / C++

Transcription:

Motivation for You want both: a list of Location objects a list of MazeMonster objects 1 How can you accomplish this by writing one LinkedList class? state all the ways you can think of doing this state the pros/cons of each method

One Way to Look at... 2 Until now, we have used variables: The type of a variable is fixed when you write code. The value of a variable isn t fixed when you write code. With templates, type isn t fixed when you write code! With templates, you use a type more or less as a variable!

Example: Queue of some type Foo C++ keywords Name of template 3 template <class Foo> class QueueT { Parameter, can be any type private: Foo Buffer[100]; int Head, Tail, Count; public: QueueT(); void Enqueue(const Foo& item); Foo Dequeue(); ~QueueT(); ; The header of a templated class declaration specifies one or more type names which are then used within the template declaration. These type names are typically NOT standard or user-defined types, but merely placeholder names that serve as formal parameters.

C++ 4 Definition of template : Parameterized class with formal parameters that denote unknown types. Usage: In situations where the same algorithms and/or data structures need to be applied to different data types. Declaration syntax: template <class Foo> class Queue { // template member declarations go here ;

What can a type parameter be used for? 5 To specify the type specifying of data which will be local to objects of the class: private: Foo Buffer[100]; To specify the type of a parameter to a class member function: void Enqueue(const Foo& item); To specify the return type of a class member function: Foo Dequeue();

Instantiating a Template Given the template declaration: template <class Foo> class QueueT {...; 6 Instantiate QueueT of objects in two ways: QueueT<Location> LocationQueue; typedef QueueT<int> IntegerQueue; IntegerQueue intqueue; Each of these defines an object which is derived from the template QueueT. Note how an actual type (Location or int) is substituted for the formal template parameter (Foo) in the object declaration.

Usage of Once created, the template object is used like any other object: 7 intqueue.enqueue(100); // add 100 to the queue intqueue.enqueue(200); // add 200 The parameter type for the member function Enqueue() was specified as Foo in the template declaration and mapped to int in the declaration of the object intqueue. When calling Enqueue() we supply an int value. int x = intqueue.dequeue(); // remove 100 intqueue.enqueue(300); // queue now // has (200,300) int Sz = intqueue.size(); // size is 2

Compiler view of templates... 8 The compiler macro expands the template code: You write QueueT<int> intqueue. Compiler emits new copy of a class named, say, QueueTint and substitutes "int" for "Foo" throughout. Therefore, the compiler must have access to the parameterized implementation of the template member functions in order to carry out the substitution. Therefore, the template implementation CANNOT be pre-compiled. Most commonly, all template code goes in the header file with the template declaration. The compiler maps the declaration: private: Foo Buffer[100]; to the declaration: The compiler mangles the template name with the actual parameter (type name) to produce a unique name for the class. private: int Buffer[100];

Implementing Template Class Methods 9 template and formal parameter(s) Class name and formal parameter(s) Scope resolution operator and function name template <class Foo> QueueT<Foo>::QueueT() { //... member function body goes here Return type goes here: template <class Foo> void QueueT<Foo>::Enqueue(Foo item) { //... member function body goes here

A Complete Template Queue Class 10 // QueueT.h #ifndef QUEUET_H #define QUEUET_H #include <cassert> const int Size = 100; template <class Foo> class QueueT { private: Foo Buffer[Size]; int Head, Tail, Count; public: QueueT(); void Enqueue(const Foo& Item); Foo Dequeue(); int getsize() const; bool isempty() const; bool isfull() const; ~QueueT(); ; //... template implementation goes here #endif Using the template parameter: data type, parameter type, return type.

A Complete Template Class 11 //... continuing header file QueueT.h template <class Foo> QueueT<Foo>::QueueT() : Head(0), Tail(0), Count(0) { template <class Foo> void QueueT<Foo>::Enqueue(Foo Item) { assert(count < Size); // die if Queue is full! Buffer[Tail] = Item; Tail = (Tail + 1) % Size; // circular array indexing Count++;

A Complete Template Class 12 //... continuing header file QueueT.h template <class Foo> Foo QueueT<Foo>::Dequeue() { assert(count > 0); // die if Queue is empty int oldhead = Head; // remember where old Head was Head = (Head + 1) % Size; // reset Head Count--; return Buffer[oldHead]; // return old Head template <class Foo> int QueueT<Foo>::getSize() const { return (Count);

A Complete Template Class 13 //... continuing header file QueueT.h template <class Foo> bool QueueT<Foo>::isEmpty() const { return (Count == 0); template <class Foo> bool QueueT<Foo>::isFull() const { return (Count >= Size); template <class Foo> QueueT<Foo>::~QueueT() { //... end template QueueT<Foo> implementation

A Driver for the QueueT Template #include <iostream> #include <iomanip> using namespace std; #include "QueueT.h" 14 void main() { const int numvals = 10; QueueT<int> intq; for (int i = 0; i < numvals; i++) { intq.enqueue(i*i); 0 0 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 int Limit = intq.getsize(); for (i = 0; i < Limit; i++) { int nextval = intq.dequeue(); cout << setw(3) << i << setw(5) << nextval << endl;

Recap 15 Note that method bodies use the same algorithms for a queue of ints or a queue of doubles or a queue of Locations But the compiler still type checks! It does a macro expansion, so if you declare QueueT<int> iqueue; QueueT<char> cqueue; QueueT<Location> Vertices; the compiler has instantiated three different classes after expansion to use with normal type checking rules.

Implicit Assumptions in QueueT Declaration of the array of Foos assumes Foo has a default constructor: template <class Foo> class QueueT { private: Foo Buffer[Size];... ; 16 Assignment of Foos assumes Foo has appropriately overloaded the assignment operator: template <class Foo> void QueueT<Foo>::Enqueue(Foo item) {... Buffer[tail] = item;... ;

Implicit Assumptions in QueueT 17 The way that Foos are returned by Dequeue() method assumes Foo has provided an appropriate copy constructor: template <class Foo> Foo QueueT<Foo>::Dequeue() {... return Buffer[oldHead];

Variable and Constant Template Parameters Template parameters may be: 18 type names (we saw this previously) variables e.g., to specify a size for a data structure constants useful to define templates for special cases (not terribly useful)

Queue Template with a Variable Parameter 19 One weakness of the QueueT template is that the queue array is of a fixed size. We can easily make that user-selectable: template <class Foo, int Size> class QueueT { private: Foo buffer[size]; int Head, Tail; int Count; public: QueueT(); bool Enqueue(Foo Item); bool Dequeue(Foo& Item); ; int getsize() const; bool isempty() const; bool isfull() const; ~QueueT(); Second template parameter is just an int variable, which falls within the class scope just as a private data member would.

Driver for Revised Queue Template 20 #include <iostream> #include <iomanip> using namespace std; #include "QueueT.h" void main() { const int smallsize = 10; const int largesize = 100; QueueT<int, smallsize> smallq; QueueT<int, largesize> largeq; for (int i = 0; i < smallsize-1; i++) smallq.enqueue(i); for (i = 0; i < largesize-1; i++) { largeq.enqueue(i); The value specified in the declaration must still be a constant though that could be avoided by redesigning the template to take the array size as a parameter to a constructor for (i = 0; i < largesize-1; i++) { int nextval; largeq.dequeue(nextval); cout << setw(3) << i << setw(5) << nextval << endl;

Template Type-checking Suppose we have the declarations: QueueT<int, 100> smallintegerqueue; QueueT<int, 1000> largeintegerqueue; QueueT<int, 1000> largeintegerqueue2; QueueT<float, 100> smallrealqueue; QueueT<float, 1000> largerealqueue; 21 Which (if any) of the following are legal assignments: smallintegerqueue = largeintegerqueue; smallintegerqueue = smallrealqueue; largeintegerqueue = largeintegerqueue2;

Linked List Template 22 // LinkListT.h #ifndef LINKLISTT_H #define LINKLISTT_H #include <cassert> #include "LinkNodeT.h" template <class Item> class LinkListT { private: LinkNodeT<Item>* Head; // points to head node in list LinkNodeT<Item>* Tail; // points to tail node in list LinkNodeT<Item>* Curr; // points to "current" node in list These are pointers to template objects so any template parameters must be specified public: explicitly. LinkListT(); LinkListT(const LinkListT<Item>& Source); ~LinkListT(); //... Function parameter is a template object, so

Linked List Template 23 //... bool isempty() const; bool atend() const; bool PrefixNode(Item newdata); bool AppendNode(Item newdata); bool InsertAfterCurr(Item newdata); bool Advance(); void gotohead(); void gototail(); bool MakeEmpty(); bool DeleteCurrentNode(); bool DeleteValue(Item Target); Item getcurrentdata() const; void PrintList(ostream& Out); LinkListT<Item>& operator=(const LinkListT<Item>& Source); ; Operator return type is a template object, so #include "LinkListT.cpp" #endif

Linked List Node Template 24 // LinkNodeT.h #ifndef LINKNODET_H #define LINKNODET_H template <class Item> class LinkNodeT { private: Item Data; LinkNodeT<Item>* Next; public: LinkNodeT(); LinkNodeT(Item newdata); void setdata(item newdata); void setnext(linknodet<item>* newnext); Item getdata() const; LinkNodeT<Item>* getnext() const; ; Function return type is a pointer to a template #include "LinkNodeT.cpp" object, so #endif

A Node Template Constructor 25 ////////////////////////////////////////////////// // Constructor for LinkNode objects with assigned // Data field. // // Parameters: // newdata Data element to be stored in node // Pre: none // Post: new LinkNode has been created with // given Data field and NULL // pointer // template <class Item> LinkNodeT<Item>::LinkNodeT(Item newdata) { Data = newdata; Next = NULL;

Node Template Mutators ////////////////////////////////////////////////// // Sets new value for Data element of object. // // Parameters: // newdata Data element to be stored in node // Pre: none // Post: Data field of object has been // modified to hold newdata // template <class Item> void LinkNodeT<Item>::setData(Item newdata) { 26 Data = newdata; ////////////////////////////////////////////////// // Suppressed to save space. // template <class Item> void LinkNodeT<Item>::setNext(LinkNodeT<Item>* newnext) { Next = newnext;

Node Template Reporters ////////////////////////////////////////////////// // Returns value of Data element of object. // // Parameters: none // Pre: object has been initialized // Post: Data field of object has been // returned // template <class Item> Item LinkNodeT<Item>::getData() const { 27 return Data; ////////////////////////////////////////////////// // Suppressed to save space. // template <class Item> LinkNodeT<Item>* LinkNodeT<Item>::getNext() const { return Next;

Linked List Template Destructor ////////////////////////////////////////////////// // Destructor for LinkListT objects. // // Parameters: none // Pre: LinkListT object has been constructed // Post: LinkListT object has been destructed; // all dynamically-allocated nodes // have been deallocated. // template <class Item> LinkListT<Item>::~LinkListT() { LinkNodeT<Item>* tokill = Head; 28 while ( tokill!= NULL) { Head = Head->getNext(); delete tokill; tokill = Head;

Linked List Template Prefix Function 29 //////////////////////////////////////////////////////////////// // Inserts a new LinkNodeT at the front of the list. // template <class Item> bool LinkListT<Item>::PrefixNode(Item newdata) { LinkNodeT<Item>* newnode = new LinkNodeT<Item>(newData); if (newnode == NULL) return false; if ( isempty() ) { newnode->setnext(null); Head = Tail = Curr = newnode; return true; newnode->setnext(head); Head = newnode; return true;

Linked List Template Assignment Overload 30 ///////////////////////////////////////////////////////////// // Deep copy assignment operator for LinkListT objects. // template <class Item> LinkListT<Item>& LinkListT<Item>:: operator=(const LinkListT<Item>& Source) { if (this!= &Source) { MakeEmpty(); // delete target's list, if any LinkNodeT<Item>* mycurr = Source.Head; // copy list while (mycurr!= NULL) { Item xferdata = mycurr->getdata(); AppendNode(xferData); mycurr = mycurr->getnext(); return *this;

Linked List Template Copy Constructor 31 ///////////////////////////////////////////////////////////// // Deep copy constructor for LinkListT objects. // template <class Item> LinkListT<Item>::LinkListT(const LinkListT<Item>& Source) { Head = Tail = Curr = NULL; LinkNodeT<Item>* mycurr = Source.Head; // copy list while (mycurr!= NULL) { Item xferdata = mycurr->getdata(); AppendNode(xferData); mycurr = mycurr->getnext();

Template Functions The template mechanism may also be used with non-member functions: 32 template <class Foo> Swap(Foo& First, Foo& Second) { Foo tmpfoo = First; First = Second; Second = tmpfoo; Given the template function above, we may swap the value of two variables of ANY type, provided that a correct assignment operation and copy constructor are available. However, the two actual parameters MUST be of EXACTLY the same type: double X = 3.14159; int a = 5; Swap(a, X); // error at compile time

Template Sort Function 33 template <class Foo> void InsertionSort(Foo* const A, int Size) { int Begin, Look; Foo Item; for (Begin = 1; Begin < Size; Begin++) { Look = Begin - 1; Item = A[Begin]; while ( Look >= 0 && A[Look] > Item) { A[Look + 1] = A[Look]; Look--; A[Look + 1] = Item; This will use the insertion sort algorithm to sort an array holding ANY type of data, provided that there are > and deep = operators for that type (if a deep assignment is logically necessary).

Doubly Linked List 34 template <typename T> class DListT { private: DNodeT<T>* Head; DNodeT<T>* Tail; public: DListT(); DListT(const DListT<T>& Source); DListT<T>& operator=(const DListT<T>& Source); ~DListT(); T* const Insert(const T& Elem); bool Delete(const T& Elem); T* const Find(const T& Elem); bool isempty() const; void Clear(); bool operator==(const DListT<T>& RHS) const; bool operator!=(const DListT<T>& RHS) const; //...

Doubly Linked List Iterator Services 35 //... code for DListT iterators goes here... //... followed by DListT services that use those iterators: iterator begin(); // iterator to 1st elem iterator end(); // iterator to last + 1 position const_iterator begin() const; // const iterators const_iterator end() const; ; T* Insert(iterator It, const T& Elem); bool Delete(iterator It);

Doubly Linked List Iterator 36 //... code for DListT iterator is inlined: class iterator { private: DNodeT<T>* Position; iterator(dnodet<t>* P) { // only a friend can create an Position = P; // iterator to a DNodeT public: iterator() { iterator operator++() { if ( Position!= NULL ) Position = Position->Next; return (*this); //... code for DListT continues...

Doubly Linked List Iterator //... code for DListT iterator continues... iterator operator++(int Dummy) { //... iterator operator--() { 37 if ( Position!= NULL ) Position = Position->Prev; return (*this); iterator operator--(int Dummy) { //... bool operator==(const iterator& RHS) const { return ( Position == RHS.Position ); bool operator!=(const iterator& RHS) const { //... //... code for DListT iterator continues...

Doubly Linked List Iterator 38 //... code for DListT iterator concludes: T& operator*() { return (Position->Element); friend class DListT<T>; // to have access to the // useful constructor... friend class const_iterator; ; // end of DListT<T>::iterator // DListT member function to give client an interator // at the start of the list: template <typename T> DListT<T>::iterator DListT<T>::begin() { return DListT<T>::iterator(Head);

Doubly Linked List Const_Iterator 39 // DListT const_iterator is very similar: class const_iterator { private: DNodeT<T>* Position; const_iterator(dnodet<t>* P) { Position = P; public: const_iterator() { const_iterator operator++() { //... if ( Position!= NULL ) Position = Position->Next; return (*this); // DListT<T>::const_iterator dereference function: const T& operator*() const { return (Position->Element);

end() 40 // DListT<T>::const_iterator dereference function: template <typename T> DListT<T>::iterator DListT<T>::end() { return DListT<T>::iterator(NULL); DListT<T>::end() returns an iterator object that points to nothing (literally). Note that the following code will result in a run-time error: DListT<T>::iterator It = D.end(); cout << *It << endl; (because the dereference operator will cause a NULL-pointer exception)