Class and Function Templates

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

Motivation for Templates

Assignment of Objects

CS201 - Introduction to Programming Glossary By

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

CS 2604 Homework 1 C++ Review Summer I 2003

Short Notes of CS201

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

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)

Lab 2: ADT Design & Implementation

COEN244: Class & function templates

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

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

Function Overloading

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

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

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

Link-Based Implementations. Chapter 4

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

ADT Sorted List Operations

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

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

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

CSCE 110 PROGRAMMING FUNDAMENTALS

GEA 2017, Week 4. February 21, 2017

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

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

CSCE 110 PROGRAMMING FUNDAMENTALS

CS302 Data Structures using C++

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

Instantiation of Template class

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

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

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

CS 1704 Intro Data Structures and Software Engineering Test 2 Fall 2001 READ THIS NOW!

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

EECE.3220: Data Structures Spring 2017

Introducing C++ to Java Programmers

Introduction to C++ Systems Programming

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

CS302 - Data Structures using C++

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

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

Intermediate Programming, Spring 2017*

Chapter 9 Classes : A Deeper Look, Part 1

Object Oriented Design

Due Date: See Blackboard

Scope. Scope is such an important thing that we ll review what we know about scope now:

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

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

Propedéutico de Programación

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

Linked List using a Sentinel

pointers & references

CMSC 341 Lecture 7 Lists

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

C++ Basics. Rationale for the C++ Class. Rationale for the C++ Class. Encapsulation and Information Hiding. Interface for a Simple Date Class

CSCI 123 Introduction to Programming Concepts in C++

Dynamic Data Structures

CPSC 427: Object-Oriented Programming

Chapter 18: Stacks And Queues

Object-Oriented Principles and Practice / C++

ADT Unsorted List. Outline

Chapter 18: Stacks And Queues

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

C++ Object-Oriented Programming

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

Financial computing with C++

Chapter 18: Stacks And Queues. Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Object-Oriented Programming

Faculty of Information and Communication Technologies

Data Structures and Algorithms

ADTs: Stacks and Queues

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

Implementing an ADT with a Class

! 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)

III. Classes (Chap. 3)

CPSC 427: Object-Oriented Programming

Chapter 12 - Templates

CSC1322 Object-Oriented Programming Concepts

COMP 2355 Introduction to Systems Programming

1 Short Answer (7 Points Each)

CS24 Week 3 Lecture 1

COMP322 - Introduction to C++ Lecture 07 - Introduction to C++ classes

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

CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation

Practice Problems CS2620 Advanced Programming, Spring 2003

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

CS212 - COMPUTATIONAL STRUCTURES AND ALGORITHMS

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Doubly-Linked Lists

! 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)

ADT: Design & Implementation

An Introduction to Queues With Examples in C++

CSE 333 Midterm Exam Cinco de Mayo, 2017 (May 5) Name UW ID#

ComS 228 Exam 1. September 27, 2004

Object-Oriented Principles and Practice / C++

SFU CMPT Topic: Class Templates

ADTs in C++ In C++, member functions can be defined as part of a struct

eingebetteter Systeme

Transcription:

Class and Function 1 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates... Implementing Template Class Methods A Complete Template Queue Class A Driver for the QueueT Template Recap Implicit Assumptions in QueueT Variable and Constant Template Parameters Queue Template with a Variable Parameter Driver for Revised Queue Template Template Type-checking Linked List Template Linked List Node Template A Node Template Constructor Node Template Mutators Node Template Reporters Linked List Template Destructor Linked List Template Prefix Function Linked List Template Assignment Overload Linked List Template Copy Constructor Template Functions Template Sort Function

Motivation for You want both: a list of Location objects a list of MazeMonster objects 2 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... 3 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 4 template <class Foo> class Queue { Parameter, can be any type private: Foo buffer[100]; int head, tail, count; public: Queue(); void Insert(Foo item); Foo Remove(); ~Queue(); ; 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++ 5 Definition of template : Parameterized class with 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 parameter be used for? 6 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 Insert(Foo item); To specify the return type of a class member function: Foo Remove();

Instantiating a Template Given the template declaration: template <class Foo> class Queue {...; 7 Instantiate Queue of ints in 2 ways: Queue<Location> intqueue; typedef Queue<int> IntegerQueue; IntegerQueue intqueue; Both of these define an object intqueue. Note how an actual type (Location or int) is substituted for the template parameter (Foo) in the object declaration.

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

Compiler view of templates... 9 The compiler macro expands the template code: You write Queue<int> intqueue. Compiler emits new copy of a class named Queueint and substitutes <int> for <Foo> throughout. Therefore, the compiler must have access to the 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: Queueint buffer[100];

Implementing Template Class Methods 10 template and actual parameter(s) Class name and actual parameter(s) Scope resolution operator and function name template<class Foo> Queue<Foo>::Queue() { //... member function body goes here Return type goes here: template<class Foo> void Queue<Foo>::Insert(Foo item) { //... member function body goes here

A Complete Template Queue Class 11 // 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(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 12 //... 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 13 //... 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 14 //... 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 - 1); 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" 15 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 16 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 three different classes after expansion to use with normal type checking rules.

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

Implicit Assumptions in QueueT 18 The way that Foos are returned by Remove() method assumes Foo has provided an appropriate copy constructor: template <class Foo> Foo Queue<Foo>::Remove() {... return buffer[val];

Variable and Constant Template Parameters Template parameters may be: 19 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 20 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 21 #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 < smallsize-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; 22 Which (if any) of the following are legal assignments: smallintegerqueue = largeintegerqueue; smallintegetqueue = smallrealqueue; largeintegerqueue = largeintegerqueue2;

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

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

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

A Node Template Constructor 26 ////////////////////////////////////////////////// // 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 ItemType> LinkNodeT<ItemType>::LinkNodeT(ItemType 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 ItemType> void LinkNodeT<ItemType>::setData(ItemType newdata) { 27 Data = newdata; ////////////////////////////////////////////////// // Suppressed to save space. // template <class ItemType> void LinkNodeT<ItemType>::setNext(LinkNodeT<ItemType>* 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 ItemType> ItemType LinkNodeT<ItemType>::getData() const { 28 return Data; ////////////////////////////////////////////////// // Suppressed to save space. // template <class ItemType> LinkNodeT<ItemType>* LinkNodeT<ItemType>::getNext() const { return Next;

Linked List Template Destructor 29 ////////////////////////////////////////////////// // 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 ItemType> LinkListT<ItemType>::~LinkListT() { LinkNodeT<ItemType>* tokill = Head; while ( tokill!= NULL) { Head = Head->getNext(); delete tokill; tokill = Head;

Linked List Template Prefix Function 30 //////////////////////////////////////////////////////////////// // Inserts a new LinkNodeT at the front of the list. // template <class ItemType> bool LinkListT<ItemType>::PrefixNode(ItemType newdata) { LinkNodeT<ItemType>* newnode = new LinkNodeT<ItemType>(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 31 ///////////////////////////////////////////////////////////// // Deep copy assignment operator for LinkListT objects. // template <class ItemType> LinkListT<ItemType>& LinkListT<ItemType>:: operator=(const LinkListT<ItemType>& Source) { if (this!= &Source) { MakeEmpty(); // delete target's list, if any LinkNodeT<ItemType>* mycurr = Source.Head; // copy list while (mycurr!= NULL) { ItemType xferdata = mycurr->getdata(); AppendNode(xferData); mycurr = mycurr->getnext(); return *this;

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

Template Functions 33 The template mechanism may also be used with non-member functions: 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 34 template <class Foo> 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).