Copyright © 1999-2014 Curt Hill Generic Classes Template Classes or Container Classes.

Slides:



Advertisements
Similar presentations
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 14: Overloading and Templates
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
 2006 Pearson Education, Inc. All rights reserved Templates.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
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.
Lecture 9 Concepts of Programming Languages
 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.
Abstract Data Types and Encapsulation Concepts
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
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.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Programming in Java CSCI-2220 Object Oriented Programming.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
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.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Chapter 6 Lists Plus. What is a Class Template? A class template allows the compiler to generate multiple versions of a class type by using type parameters.
Chapter 13: Overloading and Templates. Objectives In this chapter, you will – Learn about overloading – Become familiar with the restrictions on operator.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
(1) ICS 313: Programming Language Theory Chapter 11: Abstract Data Types (Data Abstraction)
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 10 Abstraction - The concept of abstraction is fundamental in programming - Nearly all programming.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Copyright © 2009 – Curt Hill Standard Template Library An Introduction.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright © Curt Hill Generic Functions Separating Data Type from Logic.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
 2006 Pearson Education, Inc. All rights reserved Templates.
Inheritance in C++ How to do it Copyright © Curt Hill
C++ Templates.
Distinguishing logic from data type
Introduction to C++ Systems Programming.
Lecture 9 Concepts of Programming Languages
Abstract Data Types and Encapsulation Concepts
A brief look at some of the new features introduced to the language
Abstract Data Types and Encapsulation Concepts
Packages and Interfaces
Arrays in Java What, why and how Copyright Curt Hill.
Andy Wang Data Structures, Algorithms, and Generic Programming
Lecture 9 Concepts of Programming Languages
Chapter 11 Abstraction - The concept of abstraction is fundamental in
Presentation transcript:

Copyright © Curt Hill Generic Classes Template Classes or Container Classes

Copyright © Curt Hill Why? The idea of either generic functions or classes is to separate the logic from the data handled Recall that a sort does not care much what the data type is – the logic is the same There are two ways to do this: –Polymorphism –Generics

Copyright © Curt Hill Polymorphism We can separate logic and data with polymorphism Make an inheritance tree that contains all the relevant data types Make sure that they all have the needed operations, usually assignment and comparison Let the run-time system determine and use the correct operations

Copyright © Curt Hill Generics The generic function or class has a compile-time parameter of type to be handled As long as this type has the correct properties it may be used Conceptually it is similar to using a group replace on a piece of code –Each reference to TYPE is replaced with the needed type –Then the result is compiled

Copyright © Curt Hill Tradeoffs Polymorphism requires run-time overhead –The type must be determined –This type is use to select the correct method Generics put the overhead at compile-time –Make the compiler do much more work –In a compile once, run many times environment this is the economical way

Copyright © Curt Hill Templates The reserved word for these is template This is usually followed by a parameter list: template –Reserved word ‘class’ or ‘typename’ precedes the generic name of the type –TYPE is user defined name of the generic type –TYPE does not have to be an object type

Copyright © Curt Hill Container Classes Most of the template classes implement well known data structures: list tree or map set stack or queue The operation of any of these is mostly independent of the data carried All that is required is that the contained data has certain operators such as assignment and comparison These are storage or organizing classes

Copyright © Curt Hill Template Set object Suppose a set class exists The template version would be essentially the same if we changed the define from int to double We would just have to rename our class to double_set as well Rather than doing that C++, has the template feature which makes this easy and painless

Copyright © Curt Hill First example Recall our set class header: class Set{ … }; // end class To make this a container class header: template class Set { … }; // end class Prefix the class with: template

Original Set Copyright © Curt Hill #define TYPE int class set{ private: // dynamic array one member entry TYPE * s; unsigned short int used,size; … public: set(); // Default constructor set(TYPE a); ~set(); set operator + (const set &)const; set operator * (const set &)const; …

Template Set Copyright © Curt Hill template class set{ private: // dynamic array one member entry TYPE * s; unsigned short int used,size; … public: set(); // Default constructor set(TYPE a); ~set(); set operator + (const set &)const; set operator * (const set &)const; …

Copyright © Curt Hill Discussion The TYPE will be the type name of the type we will parameterize the template with (or the type we want the class to contain) From then on TYPE will be used as if it is a previously known type From that point on Set is a peculiar type: it must be parameterized with the type that we want it to contain This is a compile-time parameter

Copyright © Curt Hill Using it in client code To declare sets in client code we do the following: set is; set rs; Each occurrence of the name Set must be accompanied by a type in angle brackets The thing in angle brackets needs to be a type suitable for assignment and comparison for set –May be natural or overloaded

Copyright © Curt Hill Discussion Set is now templatized –Remember you saw it first here The type cannot be referenced without mention of the carried type This is always in angle brackets How is the regular set different than the templatized set implementation? –Each method is preceded by template –Any reference to the type is the generic type

Inside and Outside Did you notice the discrepancy? In the header we just use set –This refers to the templatized type –It is under the template In the client code we must always parameterize it –set The implementation code has some complications as well Copyright © Curt Hill

Implementation code For regular Set + set set::operator + (const set & y)... For template set + template set set ::operator + (const set & b) const{

Copyright © Curt Hill Set as a type Client code: –Always parameterized Header –Never parameterized except by template Implementation –Prefix to scope resolution operator must be parameterized –Return types as well

Example Usual template set set ::operator + (const set & b) const{ Acceptable template set set ::operator + (const set & b) const{ Copyright © Curt Hill

Constructors The constructor name has two meanings When defining it functions like a method name so does not need the brackets: template Set ::Set(){… When called it functions like a type in a cast – does need type: s = Set ();

Copyright © Curt Hill Effect The runtime effect is the same as if the different classes were manually generated The compiler reprocesses the source each time it finds a reference to a template class method that it has not previously processed The source of the template (ie. implementation) must be available –Usually in the header file

Copyright © Curt Hill Example (1) Suppose the following: set is; set fs(4.5); is = set (8)+set (2); What does the compiler do? Before encountering this it must have seen the template definition of Set and all its method implementations

Copyright © Curt Hill Example (2) When it sees this: set is; It now rescans the header Does the substitution with int to calculate the space to reserve It also processes the default constructor after doing the substitution for int

Copyright © Curt Hill Example (3) When it sees this: set fs(4.5); It now rescans the header again Does the substitution with float to calculate the space to reserve It also processes the single type constructor after doing the substitution for float

Copyright © Curt Hill Example (4) When it sees this: is = Set (8)+Set (2); It now rescans the header again It processes the single type constructor after doing the substitution for int It processes the + operator after doing the substitution for int It processes the = operator after doing the substitution for int

Copyright © Curt Hill Example Discussion Very few compilation problems can be found in the initial pass of the template class –Usually only things having to do with the template line Compile errors are mostly found when the substitution is done and methods recompiled These occur when the code requires a property that the substituted type does not possess

Copyright © Curt Hill Form of Header File Short classes may do everything in class header Longer classes usually have a header followed by implementations –Makes the header easier to read –These are still in the.h file –Each is prefaced by the template construction There is no.CPP file, all is in.H

Style How do we do the implementation? Two styles: –The Java Style –The C++ Style Which one do you think I prefer? Copyright © Curt Hill

Java Style No function headers – everything is implemented immediately template class MyClass{ public: MyClass(){ …} Copyright © Curt Hill

Development The typical method for a template class is: Develop a standard class of the right flavor and test Use a contained type such as float –A type that would not otherwise be used Place all the code in a header Prefix each item with a template construction Replace all the floats with the generic type

C++ Style Many template directives template class MyClass{ public: MyClass(); … }; // end of MyClass template MyClass ::MyClass{ …} Copyright © Curt Hill

Template Construction Prefaces just one unit –Usually a class, function, or method –The class reserved word must be followed by the generic type Multiple parameters are allowed: template –T, U, V are user defined names –By convention uppercase –The scope of these is just the following unit –Instantiation must have three types

Copyright © Curt Hill Nesting A template class may contain another template class: map > tree; Notice that the two > cannot be adjacent or the lexical analyzer determines that it is the >> operator map and list are both Standard Template Library container classes

Template Friends Previously we saw classes which are friends A linked list is a good example: –The node –The root –The iterator Root and iterator are friends of one another and both are friends of node How is this done? Copyright © Curt Hill

Declaration The forward declaration needs a template, but the type is not used: template class LinkedList; When it is declared as a friend the type is present: template class ListNode{ friend class LinkedList ; A friend function works similarly Copyright © Curt Hill

The end of this One of the positive outcomes of the introduction of templates is the development of the Standard Template Library (STL) There are several container classes that have been developed These have a standard interface which usually include several flavors of iterators This usually comes with compiler

DevC++ Error Shows an odd error, not seen in other compilers –If the method parameter names change errors ensue Example: template class CX{ void f(int a); …}; template void CX ::f(int b){ Copyright © Curt Hill

Other Template Libraries Peer reviewed portable C++ libraries – Matrix Template Library – Windows Template Library – OO Template Library – Scientific Computing – Iterative Method Library –