 2006 Pearson Education, Inc. All rights reserved. 1 2525 2525 Templates.

Slides:



Advertisements
Similar presentations
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Advertisements

C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Functions.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
 2006 Pearson Education, Inc. All rights reserved Templates.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Function and Class Templates.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
 2006 Pearson Education, Inc. All rights reserved Arrays.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 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.
 2006 Pearson Education, Inc. All rights reserved Generics.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
Templates Outlines 1. Introduction 2. Function Templates 3. Overloading Function Templates 4. Class Templates.
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.
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.
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
Templates Zhen Jiang West Chester University
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Data Structures Using C++ 2E
 2006 Pearson Education, Inc. All rights reserved Arrays.
 2008 Pearson Education, Inc. All rights reserved Function Call Stack and Activation Records Data structure: collection of related data items.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
CS240 Computer Science II Function and Class Templates (Based on Deitel) Dr. Erh-Wen Hu.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
The Standard Template Library Container Classes Version 1.0.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 22 - C++ Templates Outline 22.1Introduction.
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Ders Notu 8 - Template İçerik 11.1 Giriş 11.2 Fonksiyon Template ları 11.3 Overloading Fonksiyon Templates.
 2006 Pearson Education, Inc. All rights reserved Templates.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Template, Preprocessing Lecture 9 November 2, 2004.
 2006 Pearson Education, Inc. All rights reserved Functions and an Introduction to Recursion.
C++ Templates.
Chapter 18 Introduction to Custom Templates
Chapter 14 Templates C++ How to Program, 8/e
Introduction to Custom Templates
Standard Template Library (STL)
CS212: Object Oriented Analysis and Design
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Standard Template Library
Standard Template Library
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Presentation transcript:

 2006 Pearson Education, Inc. All rights reserved Templates

 2006 Pearson Education, Inc. All rights reserved. 2 OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.  To distinguish between function templates and function-template specializations.  To use class templates to create a group of related types.  To distinguish between class templates and class-template specializations.  To overload function templates.

 2006 Pearson Education, Inc. All rights reserved Introduction 25.2 Function Templates 25.3 Overloading Function Templates 25.4 Class Templates 25.5 Nontype Parameters and Default Types for Class Templates

 2006 Pearson Education, Inc. All rights reserved Introduction Generic programming – Writing code in a way that is independent of any particular data type Templates are the foundation of generic programming Function templates and class templates – Enable programmers to specify an entire range of related functions and related classes Called function-template specializations and class-template specializations, respectively – A template is a blueprint for creating a function or a class – E.g, vector is a template class in C++ standard library vector, vector are classes generated from the vector template

 2006 Pearson Education, Inc. All rights reserved Introduction Example of function template int compare(const string &v1, const string &v2) { if (v1 < v2) return -1; if (v2 < v1) return 1; return 0; } int compare(const double &v1, const double &v2) { if (v1 < v2) return -1; if (v2 < v1) return 1; return 0; } template int compare(const T &v1, const T &v2) { if (v1 < v2) return -1; if (v2 < v1) return 1; return 0; } cout << compare(1, 0) << endl; string s1 = “ hi ”, s2 = “ world ” ; cout << compare(s1, s2) << endl;

 2006 Pearson Education, Inc. All rights reserved Function Templates Function Templates – Used to produce overloaded functions that perform identical operations on different types of data Programmer writes a single function-template definition Compiler generates separate object-code functions (function- template specializations) based on argument types in calls to the function template – Similar to macros in C, but with full type checking

 2006 Pearson Education, Inc. All rights reserved Function Templates (Cont.) Function-template definitions – Preceded by a template header Keyword template template parameter list – Enclosed in angle brackets ( ) – Each template parameter is preceded by keyword class or keyword typename (both are interchangeable) – Used to specify types of arguments to, local variables in and return type of the function template Examples – template

 2006 Pearson Education, Inc. All rights reserved. 8 Outline fig26_01.cpp (1 of 2) Type template parameter T specified in template header

 2006 Pearson Education, Inc. All rights reserved. 9 Outline fig26_01.cpp (2 of 2) Creates a function-template specialization of printArray where int replaces T Creates a function-template specialization of printArray where double replaces T Creates a function-template specialization of printArray where char replaces T

 2006 Pearson Education, Inc. All rights reserved. 10 Common Programming Error 26.2 If a template is invoked with a user-defined type, and if that template uses functions or operators (e.g., ==, +, <=) with objects of that class type, then those functions and operators must be overloaded for the user-defined type. Forgetting to overload such operators causes compilation errors.

 2006 Pearson Education, Inc. All rights reserved. 11 Performance Tip 25.1 Although templates offer software-reusability benefits, remember that multiple function-template specializations and class-template specializations are instantiated in a program (at compile time), despite the fact that the template is written only once. These copies can consume considerable memory. This is not normally an issue, though, because the code generated by the template is the same size as the code the programmer would have written to produce the separate overloaded functions.

 2006 Pearson Education, Inc. All rights reserved Overloading Function Templates A function template may be overloaded – Other function templates that specify the same name but different parameters – Nontemplate functions that specify the same name but different parameters – The compiler chooses the best function or specialization to match the function call A nontemplate function is chosen over a template specialization in case of a tie Otherwise, multiple matches results in a compilation error (the compiler considers the function call to be an ambiguous function call )

 2006 Pearson Education, Inc. All rights reserved. 13 Common Programming Error 26.3 If no matching function definition can be found for a particular function call, or if there are multiple matches, the compiler generates an error.

 2006 Pearson Education, Inc. All rights reserved Class Templates Class templates – Class-template definitions are preceded by a header Such as template – Type parameter T can be used as a data type in member functions and data members – Additional type parameters can be specified using a comma-separated list As in template

 2006 Pearson Education, Inc. All rights reserved. 15 Software Engineering Observation 26.2 Class templates encourage software reusability by enabling type-specific versions of generic classes to be instantiated. E.g., a stack is a general data structure, which can be used to hold integers, or strings. Given a class template of stack, we are able to create many stack classes such as “ stack of int ”, “ stack of double ”, “ stack of string ”, etc.

 2006 Pearson Education, Inc. All rights reserved. 16 Outline Stack.h (1 of 3) Create class template Stack with type parameter T Member functions that use type parameter T in specifying function parameters

 2006 Pearson Education, Inc. All rights reserved. 17 Outline Stack.h (2 of 3) Data member stackPtr is a pointer to a T Member-function template definitions that appear outside the class-template definition begin with the template header

 2006 Pearson Education, Inc. All rights reserved. 18 Outline Stack.h (3 of 3)

 2006 Pearson Education, Inc. All rights reserved. 19 Outline fig26_03.cpp (1 of 3) Create class-template specialization Stack where type double is associated with type parameter T

 2006 Pearson Education, Inc. All rights reserved. 20 Outline fig26_03.cpp (2 of 3) Create class-template specialization Stack where type int is associated with type parameter T

 2006 Pearson Education, Inc. All rights reserved. 21 Outline fig26_03.cpp (3 of 3)

 2006 Pearson Education, Inc. All rights reserved. 22 Standard Template Library The heart of the C++ standard library is the standard template library (STL). STL is a generic library that provides solutions to managing collections of data with modern and efficient algorithms. It provides a bunch of collection classes that meet different needs, together with several algorithms that operate on them. All components of STL are templates, so they can be used for arbitrary element types. STL components: Containers: used to manage collections of objects of a certain kind Iterators: used to step through the elements of collections of objects Algorithms: used to process the elements of collections, e.g., search, sort, modify, etc. Algorithms use iterators.

 2006 Pearson Education, Inc. All rights reserved. 23 Standard Template Library

 2006 Pearson Education, Inc. All rights reserved. 24 Library vector type A vector is an ordered collection of objects of a single type, each of which has an associated integer index vector is one example of container because it contains other objects. It provides random access, like array in C. It provides good performance if you append or delete elements at the end vector is a class template E.g., vector, vector, etc. #include using std::vector;

 2006 Pearson Education, Inc. All rights reserved. 25 Define and initialize vectors vector v1;vector that holds objects of type T; vector v2(v1);v2 is a copy of v1 vector v3(n, i);v3 has n elements with value i vector v4(n);v4 has n copies of a value-initialized object Ways to initialize vector

 2006 Pearson Education, Inc. All rights reserved. 26 vector operations v.empty()Returns true if v is empty; otherwise returns false v.size()Returns number of elements in v v.capacity()Returns the maximum possible number of elements without reallocation v.max_size()Returns the maximum number of elements possible v.reserve()Enlarges capacity, if not enough yet v[n], v.at(n)Returns the element at position n in v v.front(), v.back()Returns the first (last) element v1 = v2Replaces elements in v1 by a copy of elements in v2 v1 == v2Returns true if v1 and v2 are equal !=,, >=Have their normal meanings

 2006 Pearson Education, Inc. All rights reserved. 27 Insert and Remove Operations v.insert(pos, elem)Inserts at iterator position pos a copy of elem and returns the position of the new element v.insert(pos, n, elem)Inserts at iterator position pos n copies of elem v.push_back(t)Adds element with value t to end of v v.pop_back()Removes the last element v.erase(pos)Removes the element at iterator position pos and returns the position of the next element v.erase(beg, end)Removes all elements of the range [beg, end) and returns the position of the next element v.clear()Removes all elements

 2006 Pearson Education, Inc. All rights reserved. 28 Iterator Functions c.begin()Returns a random access iterator for the first element c.end()Returns a random access iterator for the position after the last element c.rbegin()Returns a reverse iterator for the first element of a reverse iteration c.rend()Returns a reverse iterator for the position after the last element of a reverse iteration

 2006 Pearson Education, Inc. All rights reserved. 29 #include using namespace std; int main() { vector coll; vector ::iterator pos; coll.push_back(2); coll.push_back(5); coll.push_back(4); coll.push_back(1); coll.push_back(6); coll.push_back(3); pos = min_element(coll.begin(), coll.end()); cout << “ min: ” << *pos << endl; pos = max_element(coll.begin(), coll.end()); cout << “ max: ” << *pos << endl; sort(coll.begin(), coll.end()); pos = find(coll.begin(), coll.end(), 3); reverse(pos, coll.end()); for (pos = coll.begin; pos!=coll.end(); ++pos) { cout << *pos << ‘ ’ ; } cout << endl; return 0; } Example 1

 2006 Pearson Education, Inc. All rights reserved. 30 #include using namespace std; int main() { vector sentence; sentence.reserve(5); sentence.push_back("Hello,"); sentence.push_back("how"); sentence.push_back("are"); sentence.push_back("you"); sentence.push_back("?"); copy(sentence.begin(), sentence.end(), ostream_iterator (cout, " ")); cout << endl; Example 2

 2006 Pearson Education, Inc. All rights reserved. 31 cout << " max_size(): " << sentence.max_size() << endl; cout << " size(): " << sentence.size() << endl; cout << " capacity(): " << sentence.capacity() << endl; swap(sentence[1], sentence[3]); sentence.insert(find(sentence.begin(), sentence.end(), "?"), "always"); sentence.back() = "!"; copy(sentence.begin(), sentence.end(), ostream_iterator (cout, " ")); cout << endl; cout << " max_size(): " << sentence.max_size() << endl; cout << " size(): " << sentence.size() << endl; cout << " capacity(): " << sentence.capacity() << endl; } Example 2 (cont.)