C++ Templates Gordon College CPS212. Overview Templates Definition: a pattern for creating classes or functions as instances of the template at compile.

Slides:



Advertisements
Similar presentations
A C LOSER L OOK AT C LASSES 1. A SSIGNING O BJECTS One object can be assigned to another provided that both objects are of the same type. It is not sufficient.
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Class and Objects.
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,
Class template Describing a generic class Instantiating classes that are type-specific version of this generic class Also are called parameterized types.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Templates and Polymorphism Generic functions and classes.
Chapter 14: Overloading and Templates
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Class Array template The array class defined in last week manipulate array of integer If we need to define class of array for float, double data type,
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
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.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
Templates and Polymorphism Generic functions and classes
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
CMSC 202 Lesson 23 Templates II. Warmup Write the templated Swap function _______________________________ void Swap( ________ a, ________ b ) { _______________.
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.
Containers Overview and Class Vector
CSCI 383 Object-Oriented Programming & Design Lecture 13 Martin van Bommel.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
J. P. Cohoon and J. W. Davidson © 1997 McGraw-Hill, Inc. Templates Generic functions and classes.
1 Inside the Vector Class: with additional needed methods CPS212CPS212 Gordon College.
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Templates Class Templates Used to specify generic class types where class members data types can be specified as parameters, e.g. here is a generic List.
Data Structures Using C++1 Chapter 3 Pointers Dr. Liu.
Overview of C++ Templates
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
1 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
OPERATOR OVERLOADING WEEK 4-5 CHAPTER 19. class Money {private:int lira; int kurus; public: Money() {}; Money(int l, int k) { lira=l+ k/100; kurus=k%100;
Programming in C++ Michal Brabec Petr Malý. Class / Struct Class / Struct consists of: data members function members constructors destructor copy constructor.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Programming II Array of objects. this Using the this Pointer this Objects use the this pointer implicitly or explicitly. – this is – this is used implicitly.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
© 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.
C:\Temp\Templates 4 5 Use This Main Program 6.
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
 2000 Deitel & Associates, Inc. All rights reserved. 12.1Introduction Templates - easily create a large range of related functions or classes –function.
Chapter 22 - C++ Templates Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Session 03 - Templates Outline 03.1Introduction 03.2Function Templates 03.3Overloading Template Functions 03.4Class Templates 03.5Class Templates and Non-type.
Yan Shi CS/SE 2630 Lecture Notes
Procedural and Object-Oriented Programming
Learning Objectives Pointers as dada members
Chapter 22 - C++ Templates
Chapter 14 Templates C++ How to Program, 8/e
STACKS AND QUEUES UNIT 2 DS THROUGH C++.
Templates.
understanding memory usage by a c++ program
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.
Operator Overloading I
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 22 - C++ Templates
Chapter 22 - C++ Templates
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Presentation transcript:

C++ Templates Gordon College CPS212

Overview Templates Definition: a pattern for creating classes or functions as instances of the template at compile time Easily create a large range of related functions or classes Terms: Function template - the blueprint of the related functions Template instance - a specific function made from a function template (instantiating the template) Type of programming: Generic programming Template metaprogramming

Class Templates Class templates Allow type-specific versions of generic classes Format: template class ClassName{ definition } Need not use "T", any identifier will work To create an object of the class, type ClassName myObject; Use Example: Listor doubleListor;

Class Templates Template class functions Declared normally, but preceded by template Generic data in class listed as type T Binary scope resolution operator used :: Template class function definition: template MyClass ::MyClass(int size) { myArray = new T[size]; } Constructor definition - creates an array of type T

Class Template Example (see template_class_demo) template class store { public : store ( const T & item = T ()); T getValue () const ; void setValue ( const T & item); friend ostream& operator & obj) { ostr << "Value = " << obj.value; return ostr; } private : T value; }; Class Declaration

Class Template Example (see template_class_demo) // use an initialization list to assign value template store ::store ( const T & item): value(item) {} // return the current value template T store ::getValue () const { return value; } // assign the argument as the new data member value template void store ::setValue ( const T & item) { value = item; } Class Implementation

Class Template Example (see template_class_demo) int main () { // declare three different types of store objects store intStore(5); store realStore(2.718); store strStore("Template"); cout << "The values stored by the objects are:" << endl ; cout << intStore << endl ; cout << realStore << endl ; cout << strStore << endl ; cout << endl ; cout << "The concatenation:" << endl ; // access current value strStore and concatenate " Class" // update the value in strStore with the new string strStore.setValue( strStore.getValue() + " Class" ); cout << strStore << endl ; return 0; } Class Usage The values stored by the objects are: Value = 5 Value = Value = Template The concatenation: Value = Template Class Output

Class Templates and Non-type Parameters Can use non-type parameters (T) in templates Can have default argument Treated as const Example: template Listor mostRecentSalesFigures; Declares object of type: Listor This may appear in the class definition: T stackHolder[ elements ]; //array to hold stack Creates array at compile time, rather than dynamic allocation at execution time

Function Templates Defines a pattern for any number of functions whose definitions depend on the template parameters. Can overload a function template with a non-template function or with other function templates. Used throughout the STL sort, copy, for_each, etc.

Function Template Example template void selectionSort ( T arr[], int n) { int smallIndex; // index of smallest element in the sublist int pass, j; T temp; // pass has the range 0 to n-2 for (pass = 0; pass < n-1; pass++). Function Declaration

Function Template Example int itest[20]={4,7,8,9,2,12,3,2,100,34,54,67,54,4,5,87,89,4,5,23}; string stest[10]={"this", "is", "a", "test", "I", "hope", "it", "works", "It", "worked"}; for ( int i = 0;i<20;i++) cout<<" "<<itest[i]; cout<<endl; for ( int i = 0;i<10;i++) cout<<" "<<stest[i]; cout<<endl; cout << "SORTED" <<endl; selectionSort(itest, 20); for ( int i = 0;i<20;i++) cout<<" "<<itest[i]; cout<<endl; selectionSort(stest, 10); for ( int i = 0;i<10;i++) cout<<" "<<stest[i]; cout<<endl; Function Usage this is a test I hope it works It worked SORTED I It a hope is it test this worked works output

Operator Templates Create operator template in the same manner as function templates Rules for deducing argument types apply Example: Template Bigint operator+(const Bingint& x, const T& y); Bigint a; a = a + 42;//argument type deduction a = operator+ (a,42);//explicit argument type

Operator Template Example template class Array { private: T* pType; int itsSize; public: Array(int itsSize = DefaultSize); Array(const Array &rhs); ~Array(){delete [] pType;} Array& operator=(const Array&); T& operator[](int offset){ return pType[offset];} const T& operator[](int offset) const { return pType[offset];} int GetSize() const {return itsSize;} }; Operator Declaration

Operator Template Example Array theArray; Array theZoo; Animal *pAnimal; for(int i=0; i<theArray.GetSize(); i++) { theArray[i] = i*2; pAnimal = new Animal(i*3); theZoo[i] = *pAnimal; delete pAnimal; } for(int j=0; j<theArray.GetSize(); j++) { cout << "theArray[" << j << "]: "; cout << theArray[j] << ”\t\t"; cout << "theZoo[" << j << "]: "; cout << theZoo[j] << endl; } Operator usage: see template_operator_zoo