COEN244: Class & function templates

Similar documents
Object-Oriented Programming

STL: C++ Standard Library

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

(8 1) Container Classes & Class Templates D & D Chapter 18. Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University

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

CS197c: Programming in C++

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

1. The term STL stands for?

Fast Introduction to Object Oriented Programming and C++

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

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2

Cpt S 122 Data Structures. Templates

7 TEMPLATES AND STL. 7.1 Function Templates

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

When we program, we have to deal with errors. Our most basic aim is correctness, but we must

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

CE221 Programming in C++ Part 1 Introduction

Exercise 6.2 A generic container class

AN OVERVIEW OF C++ 1

Chapter 1: Object-Oriented Programming Using C++

Lecture-5. STL Containers & Iterators

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

pointers & references

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides.

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

Introduction to C++ Systems Programming

CS 162, Lecture 25: Exam II Review. 30 May 2018

Instantiation of Template class

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

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

CPSC 427: Object-Oriented Programming

Absolute C++ Walter Savitch

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation

Lesson 13 - Vectors Dynamic Data Storage

use static size for this buffer

Chapter 5. The Standard Template Library.

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

Object-Oriented Programming

Function Templates. Consider the following function:

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

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

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

19.1 The Standard Template Library

Dynamic Data Structures

Short Notes of CS201

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

C++_ MARKS 40 MIN

CS201 - Introduction to Programming Glossary By

C++ (Non for C Programmer) (BT307) 40 Hours

Advanced Systems Programming

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

CSI33 Data Structures

Introduction to Programming using C++

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

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

More C++ : Vectors, Classes, Inheritance, Templates

Tokens, Expressions and Control Structures

C++ Programming Fundamentals

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Introduction to Programming Using Java (98-388)

by Pearson Education, Inc. All Rights Reserved. 2

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

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

Exceptions, Templates, and the STL

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)

CPSC 427a: Object-Oriented Programming

C++ (classes) Hwansoo Han

IS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class

Polymorphism Part 1 1

VALLIAMMAI ENGINEERING COLLEGE

The Standard Template Library. An introduction

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Inheritance, and Polymorphism.

Motivation for Templates

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC

Object Oriented Programming. Solved MCQs - Part 2

Cpt S 122 Data Structures. Introduction to C++ Part II

Interview Questions of C++

CS201 Some Important Definitions

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

CS304 Object Oriented Programming

Review for Test 1 (Chapter 1-5)

Object Oriented Programming with c++ Question Bank

Chapter 10 Introduction to Classes

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

Programming, numerics and optimization

G52CPP C++ Programming Lecture 15

PROGRAMMING IN C++ (Regulation 2008) Answer ALL questions PART A (10 2 = 20 Marks) PART B (5 16 = 80 Marks) function? (8)

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

The Ada Standard Generic Library (SGL)

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

Object Oriented Paradigm

Advanced C++ STL. Tony Wong

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Problem Solving with C++

Transcription:

COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library (STL) c A. Amer Class templates 1

Templates With templates, you can write functions and classes that work for any appropriate built-in or programmer-defined types Object-Oriented Philosophy Data Encapsulation Classes Software Reuse Inheritance, Composition Software Extensibility Polymorphism Software Reuse & Generic Code Templates Generic (genericity = "class templates"); General (generality = solutions which are not specific) c A. Amer Class templates 2

Templates: introduction / / A f u n c t i o n t h a t swaps i t s two i n t e g e r arguments : void swap ( i n t& x, i n t& y ) { / / f o r c e s the func. to work only with i n t i n t tmp = x ; x = y ; y = tmp ; } Assume you want to swap floats, longs, Strings, Rectangles, etc. void swap ( f l o a t& x, f l o a t& y ) { / / f o r c e s the func. to work only with f l o a t f l o a t tmp = x ; x = y ; y = tmp ; } Repetition of code... c A. Amer Class templates 3

Templates: introduction / / An Array class class Array { public : Array ( i n t len =10) : len_ ( len ), data_ (new i n t [ len ] ) { } Array ( const Array & ) ; ~Array ( ) ; i n t len ( ) const { return len_ ; } const i n t& operator [ ]....... private : i n t len_ ; i n t data_ ; / / f o r c e s the array to hold only i n t... } ; Assume you want an array of float, char, string,... Repeating the above over and over for float, char, string,.. tedious c A. Amer Class templates 4

Templates A template is a "type generator": a way to fabricate many similar classes or functions from one piece of code Templates support generic programming by obviating the need for explicit statements to deal with various data types "A template is a cookie-cutter that specifies how to cut cookies that all look pretty much the same (although the cookies can be made of various kinds of dough, they ll all have the same basic shape)." A template can be a Function Template or a Class Template c A. Amer Class templates 5

Function Templates A function template is the declaration of a function using templates The compiler will create a function version for every type (replacing the template) that calls the function A template function is the various instantiations of the function that the compiler creates Function Templates can be seen as an automatic way to overloading functions c A. Amer Class templates 6

Function Templates: an example / / A f u n c t i o n t h a t swaps i t s two i n t e g e r arguments : void swap ( i n t& x, i n t& y ) { i n t tmp = x ; x = y ; y = tmp ; } Assume you want to swap floats, longs, Strings, Rectangles, etc. You would have to write the same code lines except for the type Repetitions... an ideal job for a computer c A. Amer Class templates 7

Function Templates: Example template <class AType> / / scope of AType i s to the end of the f u n c t i o n void swap ( T& x, T& y ) { AType tmp = x ; x = y ; y = tmp ; } / / end scope of AType Every time swap(..) is called with a given pair of types, the compiler will go to the above definition and will create yet another "template function" as an instantiation of the above c A. Amer Class templates 8

Function Templates: Example i n t main ( ) { i n t i, j ; /... / swap ( i, j ) ; / / I n s t a n t i a t e s a swap f o r i n t f l o a t a, b ; /... / swap ( a, b ) ; / / I n s t a n t i a t e s a swap f o r f l o a t char c, d ; /... / swap ( c, d ) ; / / I n s t a n t i a t e s a swap f o r char s t r i n g s, t ; /... / swap ( s, t ) ; / / I n s t a n t i a t e s a swap f o r s t r i n g Rectangle r, q ; /... / swap ( r, q ) ; / / I n s t a n t i a t e s a swap f o r Rectangle... } Note: A "template function" is the instantiation of a "function template" A function template describes how to build a family of similar looking functions c A. Amer Class templates 9

Function Templates: special cases When a function template is called, the compiler tries to deduce the template type Most of the time it can do that successfully, but there are cases where you need to help the compiler deduce the right type For example, a function template that doesn t have any parameters of its template argument types template <class AType> void f ( ) {... } / / To c a l l t h i s f u n c t i o n with T being an i n t or a s t r i n g : void sample ( ) { f <int > ( ) ; / / type T w i l l be i n t i n t h i s c a l l f < s t r i n g > ( ) ; / / type T w i l l be s t r i n g i n t h i s c a l l } c A. Amer Class templates 10

Outline Templates Function Templates Class Templates Templates and inheritance Introduction to C++ Standard Template Library (STL) c A. Amer Class templates 11

Class Templates A class template is the declaration of a class using templates The compiler will create a class version for every type (replacing the template) that uses the class A template class is the various instantiations of the class that the compiler creates A class template is a class fabrication source for a description of how to build a family of classes that all look basically the same Class templates are often used to build type-safe containers define a container that may contain a set of integers, a set of float or any other object A template class can use other templates as its data members c A. Amer Class templates 12

Template syntax template < class T > template < typename T > / / The Standard C++ keyword typename i s interchangeable / / with the keyword class i n the template header template < class T1, class T2 > template < class T, i n t I > / / T : Type parameter ; I : Nontype parameter A template parameter can be Type parameter: the special notation typename T or class T means T is a type parameter that can be given any type as a value Nontype parameter: normal function or class style parameters, such as int i specify nontype parameters c A. Amer Class templates 13

Template = Parametrized type The term "parametrized type" is used sometime instead of "class templates" A parametrized type is a type that is parametrized over another type or some value List<int> is a type (List) parametrized over another type (int) c A. Amer Class templates 14

Container class "int Array" Consider a container class Array that acts like an array of integers: class Array { public : Array ( i n t len =10) : len_ ( len ), data_ (new i n t [ len ] ) { } Array ( const Array & ) ; ~Array ( ) { delete [ ] data_ ; } i n t len ( ) const { return len_ ; } i n t& operator [ ] ( i n t i ) { return data_ [ check ( i ) ] ; } Array& operator= ( const Array & ) ; private : i n t len_ ; i n t data_ ; i n t check ( i n t i ) const { i f ( i <0 i >= len_ ) { cout << " Bound v i o l a t i o n " ; e x i t ( 0 ) ; } return i ; } } ; Repeating the above over and over for Array of float, Student,.. is tedious c A. Amer Class templates 15

Container class "template Array" / / D e c l a r a t i o n and implementation go i n t o a header f i l e such as " Array. h " template <class AType> class Array { public : Array ( i n t len =10) : len_ ( len ), data_ (new AType [ len ] ) { } Array ( const Array <AType >&); ~Array ( ) { delete [ ] data_ ; } i n t len ( ) const { return len_ ; } AType& operator [ ] ( i n t i ) { return data_ [ check ( i ) ] ; } Array <AType>& operator= ( const Array <AType >&); private : i n t len_ ; AType data_ ; i n t check ( i n t i ) const { i f ( i <0 i >= len_ ) { cout << " Bound v i o l a t i o n " ; e x i t ( 0 ) ; } return i ; } } ; / /... implementation c A. Amer Class templates 16

Container class "template Array" i n t main ( ) { Array <int > a i ; / / array of i n t Array < f l o a t > af ; / / array of f l o a t Array <char > ac ; Array < s t r i n g > as ; Array < Array <int > > aai ; / / array of an array of i n t / / Note the space between the two > s i n the l a s t example / / Without t h i s space, the compiler would see a >> ( r i g h t s h i f t operator )... } Note: unlike template functions, template classes (instantiations of class templates) need to be explicit about the parameters over which they are instantiating c A. Amer Class templates 17

Templates definition and declaration In one header file: Template classes must be declared and defined in a header file and included together in the driver program Why? If a class definition is implemented in a separate.cpp file, then it is compiled into a separate object code file (.o) The problem arises when the various class objects are to be created in a driver Since the class was already compiled it is too late to create the automatically created overloaded classes Solution? Nothing standardized yet c A. Amer Class templates 18

Templates definition and declaration In one header file: simplified rules A template is not a class or a function A template is a "pattern" that the compiler uses to generate a family of classes or functions In order for the compiler to generate the code, it must see both the template definition (not just declaration) and the specific types/whatever used to "fill in" the template For example, if you re trying to use a Foo<int>, the compiler must see both the Foo template and the fact that you re trying to make a specific Foo<int> In most cases, the compiler options are such that a compiler doesn t remember the details of one.cpp file while it is compiling another.cpp file c A. Amer Class templates 19

Class Templates: important notes template <class AType> class Array { public : Array ( i n t l =10) : len ( l ), data_ (new AType [ l ] ) { }... private : AType data_ ; s t a t i c i n t count ;... } ; For every template class that has been created, a unique class implementation is created for that template This means that all member functions and member data (including static) are created for each template class c A. Amer Class templates 20

Class Templates: important notes You should place class declaration and class implementation in the same file *.h Wherever you reference a class object, you should include the template statement template <class Tp> double TPoint <Tp > : : getslope ( const TPoint <Tp> &p o i n t ) ; ^^^ ^^^ c A. Amer Class templates 21

Class Templates: complete example / / This would go i n t o a header f i l e such as " Array. h " template < class AType > class Array { public : Array ( i n t size = 10 ) ; Array ( const Array& ) ; ~Array ( ) ; i n t getsize ( ) const { return size ; } const Array& operator =( const Array& ) ; bool operator ==( const A r r a y& ) const ; AType& operator [ ] ( i n t index ) ; private : i n t size ; AType a r r a y P t r ; } ; c A. Amer Class templates 22

Class Templates: complete example template < class AType > Array < AType > : : Array ( i n t arraysize ) { size = ( arraysize >0? arraysize : 0 ) ; a r r a y P t r = new AType [ size ] ; } template < class AType > Array < AType > : : Array ( const Array& A ) { size = A. size ; a r r a y P t r = new AType [ A. size ] ; for ( i n t i = 0; i < size ; i ++ ) a r r a y P t r [ i ] = A. a r r a y P t r [ i ] ; } c A. Amer Class templates 23

Class Templates: complete example template < class AType > Array < AType >::~ Array ( ) { delete [ ] a r r a y P t r ; } template < class AType > const Array& Array < AType > : : operator =( const Array& A) { i f ( &A!= this ) { / / avoid s e l f assignment i f ( size!= A. size ) { delete [ ] a r r a y P t r ; size = A. size ; a r r a y P t r = new AType [ size ] ; } for ( i n t i = 0; i < size ; i ++ ) a r r a y P t r [ i ] = A. a r r a y P t r [ i ] ; } c A. Amer Class templates 24

Class Templates: complete example template < class AType > bool Array < AType > : : operator ==( const Array& A) const { i f ( size!= A. size ) { return false ; } for ( i n t i = 0; i < size ; i ++ ) i f ( a r r a y P t r [ i ]!= A. a r r a y P t r [ i ] ) return false ; return true ; } template < class AType > AType& Array < AType > : : operator [ ] ( i n t index ) { return a r r a y P t r [ index ] ; } c A. Amer Class templates 25

Class Templates: complete example / / This i s d r i v e r program #include " Array. h " i n t main ( ) { Array < i n t > i n t A r r a y ( 5 ) ; Array < char > alphabet ( 26 ) ; Array < double > double_pointer_array ( 30 ) ; Array < Student > studentarray ( 100 ) ; Array < Employee > emparray ( 50 ) ;... for ( i n t i =0; i <5; i ++) i n t A r r a y [ i ] = 0;... } return 0; c A. Amer Class templates 26

Nontype Parameters template < class T, i n t size > class Array { public : Array ( ) ; Array ( const Array& ) ; i n t getsize ( ) const { return size ; } const Array& operator =( const Array& ) ; bool operator ==( const A r r a y& ) const ; T& operator [ ] ( i n t index ) ; private : T a r r a y P t r [ size ] ; } ; void main ( ) { Array < int, 10 > i n t A r r a y ; Array < String, 200 > Two100Strings ; } Nontype template arguments must be constant c A. Amer Class templates 27

Outline Templates Function Templates Class Templates Templates and inheritance Introduction to C++ Standard Template Library (STL) c A. Amer Class templates 28

Templates and Inheritance A class template can be derived from a template class template < class T > class Base { public : T Bdata ; } ; template < class X > class Derived : public Base< i n t > { public : X Ddata ; } ; c A. Amer Class templates 29

Templates and Inheritance A class template can be derived from a non-template class class Base { public : i n t Bdata ; } ; template < class X > class Derived : public Base { public : X Ddata ; } ; c A. Amer Class templates 30

Templates and Inheritance A class template can be derived from a class template template < class T > class Base { public : T Bdata ; } ; template < class X, class Y > class Derived : public Base< Y > { public : X Ddata ; } ; c A. Amer Class templates 31

Templates and Inheritance A non-template class can be derived from a class template template < class T > class Base { public : T Bdata ; } ; template < class X > class Derived : public Base< X > { public : i n t Ddata ; } ; c A. Amer Class templates 32

Templates: comments Templates make programs larger, slower, and harder to understand Programmers design template classes or functions in exceptional cases You need, however, to understand templates to use Standard Templates Library Make sure you understand the important notes on the related slides 20 and 21 c A. Amer Class templates 33

Outline Templates Function Templates Class Templates Templates and inheritance Introduction to C++ Standard Template Library (STL) c A. Amer Class templates 34

Introduction to STL C++ provides many standard libraries such as <iostream>, <cmath>, <complex>, <vector> These standard libraries are NOT part of the language but are very convenient and useful The Standard Template Library are implemented using templates The STL save time and effort in software development The STL ensures compatibility The STL includes three key components: Containers Iterators Algorithms c A. Amer Class templates 35

STL: Containers A container is an object whose main purpose is to hold other objects that can be accessed by iterators and processed using algorithms such as sort or search Example: a vector is a container that holds objects of any type that can be inserted and removed from it Containers are defined in the namespace std and are defined as template classes in different header files Containers are template data structures c A. Amer Class templates 36

STL: Containers The standard containers and their basic operations are designed to be very similar For example: to get the number of elements in a container, use the member function size Containers are categorized as: Sequence containers Associative containers Container adapters c A. Amer Class templates 37

STL: Sequence Containers Type Description Header vector<t> a variable-sized 1D array rapid insertion and deletion at back direct access to any element list<t> a doubly linked list rapid insertion and deletion anywhere deque<t> a double-ended queue rapid insertion and deletion at front and back direct access to any element <vector> <list> <deque> c A. Amer Class templates 38

STL: Associative containers Type Description Header set<t> a set <set> multiset<t> a set: a value can occur many times <set> map<key,val> an associative array <map> multimap<key,val> a map: a value can occur many times <map> c A. Amer Class templates 39

STL: Container Adapters Type Description Header stack<t> a stack <stack> queue<t> a queue <queue> priority-queue<t> a queue: sorted by value <queue> c A. Amer Class templates 40

STL: Common Member Functions default constructor: Provide default initialization of the container copy constructor: Create a new container, initialize using another container destructor: Clean up the container empty: Returns true if no elements exist in the container max size: Returns max number of elements for the container size: Returns number of elements in the container operators (=,<,>,<=,>=, ==): Relational operator overloads swap: Swaps the elements of two containers c A. Amer Class templates 41

STL: Iterators Every container provides iterators to traverse along its elements An iterator is an object of some type and is used to refer to elements in a sequence Iterators are like pointers to a container s elements De-referencing an iterator gives access to the container s element Using ++ on an iterator move the iterator to the next element in the container c A. Amer Class templates 42

STL: Iterator Categories input: Used to read an element from a container Can move only in the forward direction output: Used to write an element to a container Can move only in the forward direction forward: Combines the capabilities of the input and output iterators and retains position in the container bidirectional: Combines the capabilities of the bidirectional iterator with the ability to directly access any element random access: bidirectional combines the capabilities of the forward iterator with the ability to move backwards c A. Amer Class templates 43

STL: Iterator Hierarchy input output forward bidirectional stronger iterator random access When a supported iterator may work on a container, then a weaker iterator will also work c A. Amer Class templates 44

STL: Supported Iterators Container vector list deque stack queue priority_queue set multiset map multimap Type of Iterator random access bidirectional random access none none none bidirectional bidirectional bidirectional bidirectional c A. Amer Class templates 45

STL: Algorithms Algorithms are the functions that may be used on a container to process its elements: insert, delete, search for, sort a container, count, etc. Algorithms use iterators to process through containers Container member function begin() returns an iterator to the first element in the container Container member function end() returns an iterator to the first position past the last element of the container c A. Amer Class templates 46

STL: Types of Algorithms Mutating-sequence algorithms: modify container Non-mutating-sequence algorithms: does not modify container Numerical algorithms: perform calculations on an entire container (found in header file <numeric>) c A. Amer Class templates 47

STL: Mutating-sequence Algorithms copy() copy backward() fill() fill n() rotate copy() rotate() generate() generate n() swap() random shuffle() transform() partition() remove() reverse copy() remove copy() remove copy if() remove if() stable partition() replace() replace copy if() replace if() reverse() unique() unique copy() c A. Amer Class templates 48

STL: Non-Mutating-sequence Algorithms adjacent find() count() count if() equal() mismatch() search() find() find each() find end() find first of() find if() search n() c A. Amer Class templates 49

STL: Numeric Algorithms accumulate() inner product() partial sum() adjacent difference() c A. Amer Class templates 50

Outline Templates Function Templates Class Templates Templates and inheritance Introduction to C++ Standard Template Library (STL) c A. Amer Class templates 51