17-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

Slides:



Advertisements
Similar presentations
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
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.
Operator Overloading Fundamentals
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
9-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
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,
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Operator Overloading in C++
Intro to Generic Programming Templates and Vectors.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
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.
20-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
13-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
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.
C++ Review (3) Structs, Classes, Data Abstraction.
18-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
3-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
2-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
11-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
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,
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 14: Overloading and Templates Overloading will not be covered.
Programming Languages and Paradigms C++. C++ program structure  C++ Program: collection of files Header files CPP source files  Files contain class,
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
Methods Awesomeness!!!. Methods Methods give a name to a section of code Methods give a name to a section of code Methods have a number of important uses.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
1 Introduction to Object Oriented Programming Chapter 10.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
16-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
14-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
CPSC 252 Templatization Page 1 Templatization In CPSC152, we saw a class vector in which we could specify the type of values that are stored: vector intData(
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Pointer to an Object Can define a pointer to an object:
Pointers and Dynamic Arrays
User-Written Functions
Computing Fundamentals with C++
C++ Templates.
Exceptions, Templates, and the Standard Template Library (STL)
Dr. Bernard Chen Ph.D. University of Central Arkansas
group work #hifiTeam
Array Lists Chapter 6 Section 6.1 to 6.3
Chapter 12 Pointers and Memory Management
Constructors and Other Tools
Chapter 4 Implementing Free Functions
Chapter 11 Generic Collections
Standard Version of Starting Out with C++, 4th Edition
Computing Fundamentals with C++
Exceptions, Templates, and the Standard Template Library (STL)
Presentation transcript:

17-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN Presentation Copyright 1999, Franklin, Beedle & Associates Students who purchase and instructors who adopt Computing Fundamentals with C++, Object-Oriented Programming and Design by Rick Mercer are welcome to use this presentation as long as this copyright notice remains intact.

17-2 Chapter 17 Templates Building Generic Classes  Chapter Objectives  Implement a function that can search and sort vectors of any class  Pass class names to container classes just like the C++ standard: bag myBookBag; // bag of book objects bag myBookBag; // bag of book objects bag myCDs; // bag of CD objects bag myCDs; // bag of CD objects  Implement generic container classes that store collections of any class of elements

Templates  Consider collection classes  store a collection of objects  provide suitable access to all elements  perhaps with the iterator pattern  so far have only stored one class of object  Instead of a bag or list of strings  how about a bag or list of anything?  let's investigate how vectors store a collection of any type of object

17-4 bag of this, bag of that  The bag class in Chapter 11 requires typedefs to inform bag which class of objects it will store  not ideal  but better than having a separate collecton class for strings, bankAccounts, grids, weeklyEmployees, and any other new object....  there is a better way  This chapter describes templates -- a mechanism that allows the type of object to be stored to be passed as an "argument" betweeen  This chapter describes templates -- a mechanism that allows the type of object to be stored to be passed as an "argument" betweeen

Function Templates  Let's start with the simpler function template  Problem: write a lesser function that returns the "lesser" of any two objects  but < is defined for the class  examples: int, double, string, or any other type you want to have meaning for less than (bankAccount e.g.)  We could write one function for each class/type  or we could use function templates

17-6 Two options  Option 1) One function per class very specific int lesser( int a, int b); int lesser( int a, int b); double lesser(double a, double b); double lesser(double a, double b); string lesser(string a, string b); string lesser(string a, string b); char* lesser( char* a, char* b); char* lesser( char* a, char* b); // And on and on and on... // And on and on and on...  Option 2) One function for any class very general  use a function template

17-7 Function Templates  General form and example function heading template that could  take any type of class argument and  return that class of argument template template function-definition template template // Now use TheClass anywhere in the function // Now use TheClass anywhere in the function TheClass lesser(TheClass a, TheClass b) TheClass lesser(TheClass a, TheClass b) { //... { //... }

17-8 Using template parameters  Return the "lesser" of any 2 arguments  TheClass must define < (See Ch 18: Operator Overloading  int, double, string, char already do template template TheClass lesser(TheClass a, TheClass b) TheClass lesser(TheClass a, TheClass b) { // pre: TheClass must define < { // pre: TheClass must define < // post: Return the lesser of the two arguments // post: Return the lesser of the two arguments TheClass result; TheClass result; if(a < b) if(a < b) result = a; result = a; else else result = b; result = b; return result; return result; }

17-9 Active Learning  What is the Output? int main() int main() { // Test drive a function template { // Test drive a function template cout << lesser(-16, 16) << endl; cout << lesser(-16, 16) << endl; cout << lesser(0.0003, 0.003) << endl; cout << lesser(0.0003, 0.003) << endl; cout << lesser('B', 'b') << endl; cout << lesser('B', 'b') << endl; cout << lesser("Aaron", "Zeke") << endl; cout << lesser("Aaron", "Zeke") << endl; return 0; return 0; } Optional Demo: funtemps.cpp

17-10 What is going on?  TheClass is a template  It becomes whatever class name (int, string,.. ) is passed to the function  Therefore, the arguments and the return type are all of the same type  For each argument type, the C++ compiler generates a function with that type  the previous main function forced the C++ compiler to generate four unique functions, each with a different type of parameter to matches the return type

17-11 The four (4) functions you get int lesser(int a, int b) { int result; if(a < b) result = a; else result = b; return result; } double lesser(double a, double b) { double result; if(a < b) result = a; else result = b; return result; } char lesser(char a, char b) { char result; if(a < b) result = a; else result = b; return result; } char* lesser(char* a, char* b) { char* result; if(a < b) result = a; else result = b; return result; }

Class Templates  You can make a class accept a template parameter  The template parameter name can be used throughout an entire class  This allows for collections of any class, for example  can have a bag of ints, doubles, books,...  just like the vector class that must have the class name between  just like the vector class that must have the class name between

17-13 Class Templates  Class templates are just like function templates except they are followed by a class definition rather than a function definition template template class-definition  This can add a lot of code to the member function implementations  unless you implement functions in the class

17-14 Consider a vector class template template class vector { public: vector(); vector(); vector(int initCapacity); vector(int initCapacity); vector(int initCapacity, vector(int initCapacity, VectorElementType initialValue); VectorElementType initialValue); vector(const vector & source); vector(const vector & source); ~vector(); ~vector(); //... //...private: VectorElementType* x; // Pointer to first of many VectorElementType* x; // Pointer to first of many};

17-15 When vector objects are constructed  The template argument passed up during construction replaces the class parameter  you get pointers to any type vector a3(7);  VectorElementType* x;  bankAccount* x; bankAccount* x; vector a4(7);  VectorElementType* x;  track* x; track* x; vector a3(7);  VectorElementType* x;  int* x; int* x; vector a3(7);  VectorElementType* x;  double* x; double* x;

Member Function Templates  When a class has been defined with a template parameter, all member functions automatically become template functions  This means that the member functions must be preceded by the same syntax template template class-name ::member-function-name(parameters) { //... member function implementation //... member function implementation}

17-17 Examples  This means a lot of stuff must be written before the member function implementations  even if there is no reference to the template parameter four words and two sets of  even if there is no reference to the template parameter four words and two sets of template template int vector ::capacity() const { return my_capacity; return my_capacity; } Extra Code

A Simple Class with a Template  To avoid all that ugly extra syntax, consider a class definition that also implements the member functions  replace ; with the function body between { and }  The following class only demonstrates the use of templates within a class  the class must define << since that operator is applied to any class of object passed to construct a Silly object

17-19 A Simple Generic Class template template class Silly { // pre: Type must define ostream << public: Silly(Type initValue) Silly(Type initValue) { value = initValue; value = initValue; } void display() void display() { // pre: Type can be output with cout << { // pre: Type can be output with cout << cout << "The value: " << value << endl; cout << "The value: " << value << endl; }private: Type value; Type value;};

17-20 The type between cause another class creation #include #include using namespace std; #include "Silly" // For class Silly // This main function will cause three classes to // be generated by the compiler with Type replaced // by int, double, and string int main() { Silly anInt(-999); Silly anInt(-999); Silly aDouble(1.23e-02); Silly aDouble(1.23e-02); Silly aString("abcdefg"); Silly aString("abcdefg"); anInt.display(); anInt.display(); aDouble.display(); aDouble.display(); aString.display(); aString.display(); return 0; return 0;} Output The value: -999 The value: The value: abcdefg The value: abcdefg

A Generic bag Class  Chapter 11 presented a container class named bag for storing a collection of objects  that bag class required a typedef before the #include to indicate what the bag could store  This section presents a generic bag class bag identifier ; bag identifier ;  This is what the C++ standard library used for its container classes like vector and list Optional Demo: p660.cpp

17-22 BagElementType  Now the BagElementType is a template parameter--it is known thoughout the class template template class bag { public: bag(); bag(); //... //... void add(BagElementType newElement); void add(BagElementType newElement); // post: Add newElement to this bag and increase // post: Add newElement to this bag and increaseprivate: BagElementType* my_data; // Pointer to first... BagElementType* my_data; // Pointer to first... //... //...};

17-23 Implement member functions with template  Any member function in bag must get the extra templates synytax when implemented outside of the class  even if BagElementType is not used in the function  notice that add checks the capacity, extra memory is allocated when the bag is full template template void bag ::add(BagElementType newElement) { // First check to see if we need to grow the bag if(my_size >= my_capacity) if(my_size >= my_capacity) { // Inadequate capacity so double the capacity { // Inadequate capacity so double the capacity my_capacity = 2 * my_capacity; my_capacity = 2 * my_capacity; //... //...

The Copy Constructor  This bag class uses a pointer  need a copy constructor and a destructor  This copy constructor will perform deep copying do not just copy the pointer  It too requires the extra template syntax  see next slide

17-25 The Copy Constructor for passing bag objects as arguments template template bag ::bag(const bag & source) { // Copy the data members (memberwise copy) // Copy the data members (memberwise copy) my_size = source.my_size; my_size = source.my_size; my_index = source.my_index; my_index = source.my_index; my_capacity = source.my_capacity; my_capacity = source.my_capacity; // Allocate the memory for the new bag // Allocate the memory for the new bag my_data = new BagElementType[my_capacity]; my_data = new BagElementType[my_capacity]; // Copy all values from source to destination // Copy all values from source to destination for(int j = 0; j < my_capacity; j++) for(int j = 0; j < my_capacity; j++) { // Deep copy copies all elements, not just the pointer { // Deep copy copies all elements, not just the pointer my_data[j] = source.my_data[j]; my_data[j] = source.my_data[j]; }}