Lecture 18 Templates, Part II. From Last Time: What is a Template? This is the “official” specification for a template. It says that to define a template.

Slides:



Advertisements
Similar presentations
Objects and Classes Part II
Advertisements

1.00 Lecture 37 A Brief Look at C++: A Guide to Reading C++ Programs.
1 Linked Lists III Template Chapter 3. 2 Objectives You will be able to: Write a generic list class as a C++ template. Use the template in a test program.
Let’s Look at Some Functions Boolean Functions – functions that return ‘true’ or ‘false’ Other Functions – some with arguments, some with none.
TEMPLATES Lecture Presented By SHERY KHAN Object Orienting Programming.
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
 2006 Pearson Education, Inc. All rights reserved Templates.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
Using Templates Object-Oriented Programming Using C++ Second Edition 11.
OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
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++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
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.
Object Oriented Programming Elhanan Borenstein Lecture #4.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Templates ~ their instantiation and specialization.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CS 11 C++ track: lecture 7 Today: Templates!. Templates: motivation (1) Lots of code is generic over some type Container data types: List of integers,
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Chapter 8: Inner Classes. You're an OO programmer, so you know that for reuse and flexibility/extensibility you need to keep your classes specialized.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Lecture 21 Multiple Inheritance. What is Multiple Inheritance? We defined inheritance earlier in the semester as a relationship between classes. If class.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Computer Engineering Rabie A. Ramadan Lecture 5.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
Lecture 17 Templates, Part I. What is a Template? In short, it’s a way to define generic functionality on parameters without needing to declare their.
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:
1 Using Templates COSC 1567 C++ Programming Lecture 10.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Overview of C++ Templates
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
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.
Classes - Part II (revisited) n Constant objects and member functions n Definition Form of Member Functions n friend functions and friend classes n Constructors.
Monday, Jan 27, 2003Kate Gregory with material from Deitel and Deitel Week 4 Questions from Last Week Hand in Lab 2 Classes.
CSIS 123A Lecture 7 Static variables, destructors, & namespaces.
Object Oriented Programming COP3330 / CGS5409.  Class Templates  Bitwise Operators.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Memory Management.
Motivation for Generic Programming in C++
Constructors and Destructors
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Introduction to C++ Systems Programming.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Java Programming Language
Constructors and Destructors
Lecture 3 More on Flow Control, More on Functions,
Presentation transcript:

Lecture 18 Templates, Part II

From Last Time: What is a Template? This is the “official” specification for a template. It says that to define a template you must: start with the keyword template specify, in angle brackets, a placeholder name for each type you are using (these aren’t necessarily classes, that’s just the name chosen for this task) follow the angle brackets with your function name follow the function name with your parameter list (using any combination of real types and placeholder names) Again, the fact that you are using the keyword class for each placeholder you are defining has nothing to do with a C++ class. At compilation time the compiler will look at your code and generate a separate function for each type used throughout your code when calling template functions. template fn (formal args)

What is a Template? Well, this is really the definition of a template function. C++ also has the notion of a template class. A template class in its simplest form is a normal class definition with one or more variable types used throughout this class. The variable types are represented by the same placeholders we saw in template functions. The “declaration” of the placeholders is done, again, with the template keyword followed by the placeholders in angled brackets. This “declaration” appears just before the class keyword. template // declare placeholders class SimpleClass// regular class definition { public: … };

What is a Template? Once I’ve declared the “placeholders” I may use them anywhere in the class as if they were real types. Just like with the function templates, the compiler takes care of substituting real types at compile time. In order to illustrate this, consider a class called MyArray which allows you to create an array of varying size with bounds checking: template // declare placeholders class SimpleClass// regular class definition { public: … };

Template Classes As you can see, storageType is used throughout the class as a placeholder for a type “to be determined” But how do we declare an instance of this class? template class MyArray { public: MyArray(); ~MyArray(); storageType& operator[](int i); bool setArrayBounds(int i); private: bool growStorage(int argArraySize); storageType *arrayStore; int arraySize; };

Template Classes Remember how template functions could be called with a specific type to coerce the placeholder argument to? Declaring an instance of a template class is similar. You must specify a type at declaration time: int main() { MyArray intArray;// Declares an instance // of MyArray with int as intArray.setArrayBounds(5);// storage type. intArray[0] = 1; intArray[1] = 2; intArray[2] = 3; intArray[3] = 4; intArray[4] = 5; return 0; }

Template Classes But, we’re getting a little ahead of ourselves. We need to provide definitions for our member functions. Each member function can be thought of as a template function and is defined like this: template bool MyArray ::setArrayBounds(int i) { if (i > arraySize) { return growStorage(i); } return true; }

Template Classes You see, in “parameterizing” the class with the placeholder for a type “to be defined” we’re actually allowing for an infinite number of classes to be created at compile time. That is why all of template keywords are necessary on the member functions. A separate class (and thus a separate set of member functions) is generated for each different type used to create an instance of this class. Constructors and Destructors have a template format as well: template MyArray ::MyArray() { arrayStore = NULL; arraySize = 0; }

Template Classes Where do you think these template member functions need to go in our source code? It would be natural to assume that they would go in a file called MyArray.cpp, whereas the template class definition would go in MyArray.h This won’t work :-(. Well, even though this looks like a definition it is actually more of a declaration. template MyArray ::~MyArray() { if (arrayStore) delete [] arrayStore; }

Template Classes Remember, the compiler needs to generate a separate set of member functions for each type used to create an instance of this class. That means that these definitions are needed at compile time, and not link time. Compiling a.cpp file containing these definitions by themselves is somewhat meaningless. The definitions are somewhat like macros and need to be present when instances of the classes they belong to are actually being declared. As such, the best place for these definitions would be in the same header file which contains the class definition. They should still be declared outside of the definition to avoid implicit inlining. Don’t believe me? Check out the string header!

Template Classes Along with our “generic” array type called MyArray, another natural candidate for a template class is the List class. Consider a generic list class which lets the type of container used as “storage” in the list be abstracted through the use of templates...

Demonstration #1 Better List

But Wait, It Gets Stranger… When creating template classes we’ve only considered that we can specify a data type in any given placeholder. You can also specify a constant expression except for floating point values. Consider the following modifications to MyArray which impose bounds restrictions on the array size:

But Wait, It Gets Stranger… Note the new piece of syntax up by the template keyword! This specifies that there is an integer value to be propagated through the class as part of the type. It’s conceptually equivalent to defining a separate class for each value of size specified with a const member variable = size. template class MyArray { public: MyArray(); ~MyArray(); storageType& operator[](int i); private: storageType arrayStore[size]; int arraySize; };

But Wait, It Gets Stranger… One of the advantages here is that I don’t need to check the validity of size. If the programmer (most likely myself) passes something totally inappropriate for size (like 0 or a negative number) the compiler will catch it (since these templates are being expanded out at compile time) template class MyArray { public: MyArray(); ~MyArray(); storageType& operator[](int i); private: storageType arrayStore[size]; int arraySize; };

But Wait, It Gets Stranger… An example of using a constant expression in a template placeholder is enforcing a limit on the size of a linked list. This isn’t as appropriate as the example just given for MyArray, because you could easily define a member function in your List class which sets the limit as well. It’s still interesting to look at, so...

Demonstration #2 Limited List

Now How Much Would You Pay? But wait, there’s more! How about template classes (with a designated type) as types passed to other templates? How about a list of Lists? int main() { // Declare an list of MyStrings List stringList; MyString ms = “This is weird”; stringList.insert(ms,0); List > myList; // <--- COOL! myList.insert(stringList,0); … }

Now How Much Would You Pay? And you thought function templates were strange! Yes, you can nest these types to an infinite depth with the usual exceptions of available system resources and sanity. There is one important point here. Notice the deliberate spaces between angle brackets on the right side of the declarations. If you defined these like this: List > The compiler would think the two angle brackets on the right were the >> operator. This is one case in the C++ compiler where whitespace matters. List > myList; List > > myListofLists; MyArray > > myArrayOfListsofArray; // You get the idea!

Demonstration #3 And, I’ll throw in a FREE demo! ListOfLists

Act Now, and I’ll Throw In Inheritance! Just call our toll-free number 1-8xx-INHERIT You might ask, how can I create a single template for one of these classes built by nesting templates? By using what LNG calls a “degenerate” form of inheritance. Instead of using List > everywhere, I can use: template class ListofLists : public List > {}; void func() { // The following creates a list of lists of integers ListOfLists listOfListsOfInt; … }

Lecture 18 Final Thoughts