Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.

Slides:



Advertisements
Similar presentations
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Advertisements

Chapter 17 Templates. Generic Algorithms Algorithms in which the actions or steps are defined, but the data types of the items being manipulated are not.
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.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Templates CS-341 Dick Steflik. Reuse Templates allow us to get more mileage out of the classes we create by allowing the user to supply certain attributes.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
Templates CS-240 Dick Steflik & DJ. Foreman. Reuse Templates allow us to get more mileage out of the classes we create by allowing the user to supply.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
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.
Intro to Generic Programming Templates and Vectors.
Templates and the STL.
Templates CS212 & CS-240. Reuse Templates allow extending our classes Allows the user to supply certain attributes at compile time. Attributes specified.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
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.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
Data Structures Using C++ 2E
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
More about Class 靜宜大學資工系 蔡奇偉副教授 ©2011. 大綱 Instance Class Members Class members can be associated with an instance of the class or with the class as a.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 4 – August 30, 2001.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
1 CSC241: Object Oriented Programming Lecture No 25.
1 Chapter 1 C++ Basics Review Reading: Sections 1.4 and 1.5.
Overview of C++ Templates
1 Chapter 1 C++ Templates Sections 1.6 and Templates Type-independent patterns that can work with multiple data types –Generic programming –Code.
Chapter 3 Templates Saurav Karmakar Spring Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates.
Mobility Research Lab mobility.ceng.metu.edu.tr Applied Innovative Interdisciplinary (AI2) Research Lab Short Course on Programming in C/C++
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Copyright © 2009 – Curt Hill Standard Template Library An Introduction.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Templates Where the TYPE is generic. Templates for functions Used when the you want to perform the same operation on different data types. The definition.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Chapter 1 C++ Templates (Sections 1.6, 1.7). Templates Type-independent patterns that can work with multiple data types. Function Templates  These define.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
1 Linked Lists Assignment What about assignment? –Suppose you have linked lists: List lst1, lst2; lst1.push_front( 35 ); lst1.push_front( 18 ); lst2.push_front(
CMSC 341 Lecture 2. Announcements Tutors wanted Office hrs Project 1.
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
17-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Copyright © Curt Hill Generic Functions Separating Data Type from Logic.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 2 Objects and Classes
Templates.
Review Bernard Chen Spring 2006.
Operator Overloading BCA Sem III K.I.R.A.S.
Templates.
Chapter 2 Objects and Classes
CMSC 202 Lesson 22 Templates I.
Templates I CMSC 202.
CMSC 341 C++ and OOP.
CMSC 341 C++ and OOP.
Chapter 3 Lists, Stacks, and Queues
Presentation transcript:

Chapter 3 Templates

Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy stuff Bugs

3.1 What is a Template? A template is a mechanism for writing routines that work for arbitrary types without knowing these types.  For example: Type independent algorithms and data structures Templates are most likely seen in generic algorithm implementations, i.e. sorting & searching.

3.2 Function Templates typedef : keyword for defining new type from an existing one. Ex: typedef double Object; Object a = 3.5; // double a = 3.5 A Function template is a design or pattern for a function which allows processors to generate an actual function from this design. A function template is not an actual function, instead it’s a design or a pattern, for what could become an actual function.

Function template example: Swap routine typedef double Object; void swap(Object & lhs, Object & rhs) { Object tmp = lhs; lhs = rhs; rhs = tmp; } // figure 3.1 Note: swap is part of the STL //Object: must have copy // constructor & operator= template void Swap(Object & lhs, Object & rhs) { Object tmp = lhs; lhs = rhs; rhs = tmp; }// figure 3.2

Swap routine used in main function: int main(){ int x =5, y = 7; double a = 2, b = 4; Swap (x,y); // swap(int,int) Swap(x,y); //reuse previous instantiation Swap(a,b); //Swap(double, double) //Swap(x, b); // illegal: no match return 0; } // figure 3.3

3.3 A Sorting Function Template template void insertionSort(vector &a){ for(int p = 1; p < a.size(); p++){ Comparable tmp = a[p]; int j; for(j = p; j > 0 && tmp < a[j-1]; j++) a[j] = a [j –1]; a[j] = tmp; }

Insertion Sort example The given insertionSort routine work for double, int, float but not char*, (primitive string), because operator “=” and “<” are undefined. sorting demo(1) sorting demo(2)

3.4 Class Templates A class can be a template.  Example: vector is a class template A call by value should not be used for parameters of the template type; use constant reference instead.

template class MemoryCell{ public: explicit MemoryCell(const Object & initVal = Object()) :storedValue(initVal){} const Object & read() const {return storedValue;} void write(const Object & x) {storedValue = x;} private: Object storedValue; }; // figure 3.8 A class template example:

Calling the class template from main: int main() { MemoryCell m; m.write(5); cout<<“Cell contents are ” <<m.read()<<endl; return 0; } When the interface is separated from the implementation, all member functions should be implemented as template functions

template class MemoryCell { public: explicit MemoryCell(const Object & initVal = Object()); const Object & read() const; const write(const Object & x); private: Object storedValue; };// figure 3.10 #include “MemoryCell.h” template MemoryCell ::MemoryCell (const Object & initVal) :storedValue(initVal){} template const Object & MemoryCell ::read() const {return storedValue;} template void MemoryCell ::write( const Object & x) {storedValue = x;} // figure 3.11 Separating the interface and implementation of the template

template class ClassName{ public: //public members private: //private member };// typical template interface template ReturnType ClassName ::memberName(parameterList) /*const*/ { // member body } // typical member implementation

Implementing the Vector Class Template Provides: Indexing, resizing, copying, and index range checking capabilities figure 3.14 vector.h figure 3.15 vector.cpp

3.5 Templates of Templates: A Matrix Class Figure 3.16 A complete matrix class Matrix class is represented as a vector of vectors. Overload operator [] for mutators and accessors No need for destructors, copy operator and assignment operator, (already exist in vector) Note: There must be at least a space between “>” “>” in the declaration; otherwise compilers will confuse “>>” with the shift operator. Ex: vector > array; // white space needed

3.6 Fancy Templates Multiple template parameters template Class Map{... }; Ex: map zipCodes; Note: class “map” is in STL

Default Template Parameters template Class Map{... }; Map m1; // keyType = int, valueType = int Map m2; // keyType = int, valueType = string Default template parameters are widely used in STL Note: some compilers do not support default template parameters

Default Template Parameters typename : a new keyword can be used instead of class template class memoryCell {... };

3.7 Bugs Associated with Templates Template STD changes frequently => incompatible compilers Matching algorithm breaks when template involve (function template) Nested templates are not widely supported Static functions & data members are often not handled correctly

Common mistakes When a class template is instantiated, all needed operations must be available.  For instance, the insertion sort template needs to have operator < defined for whatever Comparable is instantiated. Otherwise, an error will be detected at link time. Clearly state what conditions must be satisfied by the template parameters Use either reference or constant reference for parameter passing. (Page 115)

In class exercise Write a function template to sort three Comparable objects. When templates are used what types of errors are detected when the function template is scanned? What errors are detected when the function is instantiate? Describe syntax for class templates.

Summary Discussion of template facilities Template for generic algorithms