Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.

Slides:



Advertisements
Similar presentations
DATA STRUCTURES USING C++ Chapter 5
Advertisements

TEMPLATES Lecture Presented By SHERY KHAN Object Orienting Programming.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
 2006 Pearson Education, Inc. All rights reserved Templates.
 2006 Pearson Education, Inc. All rights reserved Templates.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Function and Class Templates.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 22 - C++ Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
 2006 Pearson Education, Inc. All rights reserved Generics.
Templates Outlines 1. Introduction 2. Function Templates 3. Overloading Function Templates 4. Class Templates.
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.
Object Oriented Data Structures
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
EEL 3801 Part VIII Fundamentals of C and C++ Programming Template Functions and Classes.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
CS240 Computer Science II Function and Class Templates (Based on Deitel) Dr. Erh-Wen Hu.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
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.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Overview of C++ 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.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
TEMPLATESTEMPLATES BCAS,Bapatla B.mohini devi. Templates Outline 22.1Introduction 22.2Class Templates 22.3Class Templates and Non-type Parameters 22.4Templates.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
 2000 Deitel & Associates, Inc. All rights reserved. 12.1Introduction Templates - easily create a large range of related functions or classes –function.
 2003 Prentice Hall, Inc. All rights reserved. 1 Ders Notu 8 - Template İçerik 11.1 Giriş 11.2 Fonksiyon Template ları 11.3 Overloading Fonksiyon Templates.
Templates יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום.
 2006 Pearson Education, Inc. All rights reserved Templates.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Template, Preprocessing Lecture 9 November 2, 2004.
Motivation for Generic Programming in C++
Chapter 22 - C++ Templates
C++ Templates.
Chapter 18 Introduction to Custom Templates
Chapter 14 Templates C++ How to Program, 8/e
Introduction to Custom Templates
CS212: Object Oriented Analysis and Design
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
template< class T > class Stack { public:
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Standard Template Library
Chapter 22 - C++ Templates
Chapter 22 - C++ Templates
Standard Template Library
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Standard Template Library
Presentation transcript:

Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different situations by instantiating the parameters as needed. In C, as in practically all programming languages most basic form of code that takes a parameter is a function. For example, consider this C function:

Cont.. int square (int n ) { return n * n ; } Here the expression n * n has been made parametric in n. Hence we can apply it to some integer, say square(42)

Cont… Templates take the idea of parameterizing code much further. In particular, the parameters may be types. For example, if F is a C++ template, it could be instantiated with int as the type, as in F A typical example is the standard library template vector. By instantiating it with int, as in vecor, we get a vector of integers.

Cont… Note the fundamental difference to the function square above In the function int is the type of the argument, whereas in F, the argument is int itself There are two kinds of templates in C++: 1. Class templates 2. Function templates These correspond roughly to polymorphic data types and polymorphic functions in functional languages.

Cont… To first approximation, you can think of template instantiation as substitution of the formal parameters by the actual arguments. Suppose we have a template template struct s {... T... T... };

Cont… Then instantiating the template with argument A replaces T with A in the template body That is, s works much as if we had written a definition with the arguments filled in: struct sA {... A... A... };

Cont… The reality is more complex, but details may depend on the c++ implementation. A naive compiler may cause code bloat by creating and then compiling lots of template instantiations s,s,s,…. It is an interesting question how an optimizing compiler and /or a careful template programmer may avoid this risk of potential code bloat. On the other hand, because the argument replacement happens at compile time, there is no more overhead at runtime. Templates can produce very efficient code, in keeping with the aim of C++ to provide “zero-overhead” abstractions. In C a similar form of replacement of parameters could be attempted using the macro processor. Templates, however,are far more structured than macros, which should be avoided in C++. We read template as analogous to T.

Function templates Overloaded function normally perform similar or identical operations on different types of data. If the operations are identical for each type, they can be expressed more compactly and conveniently using function templates. All function-template begins with keyword template followed by a list of template parameters to the function template enclosed in angle brackets ( );

Cont… Each template parameter that represents a type must be preceded by either of the interchangeable keywords class or typename, as in Template or Template or Template

Cont… The type template parameters of a function-template definition are used to specify the types of the arguments to the function, to specify the return type of the function and to declare variables within the function. Example: Void printarray(const int *array, int count) { for (int i=0; i<count; I++) Cout <<array[i]<<“”; cout <<endl; }

Cont… The name of a template parameter can be declared only once in the template parameter list of a template header,but can be used repeatedly in function’s header and body. Template parameter names among function templates need not be unique.

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one. Templates are very useful when implementing generic constructs like vectors, stacks, lists, queues which can be used with any arbitrary type C++ templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code. There are two kinds of templates: function templates and class templates Use function templates to write generic functions that can be used with arbitrary types. For example, one can write searching and sorting routines which can be used with any arbitrary type. The Standard Template Library generic algorithms have been implemented as function templates, and the containers have been implemented as class templates Function templates A function template behaves like a function except that the template can have arguments of many different types In other words; a function template represents a family of functions. The general format of a function template is as follows: template return type functionname(argument of type T ) { // body of function with Type T } The following example declares a function template max(x, y) which returns either x or y, whichever is larger template myType max (myType a, myType b) { return (a>b?a:b);} The above definition of function max() can work with different kinds of data types. A function template does not occupy space in memory. The actual definition of a function template is generated when the function is called with a specific data type. The function template does not save memory.

Class templates Class templates are called parameterized types,because they require one or more type parameters to specify how to customize a “generic class” template to form a class- template specialization. Example: Stack – a datastructure into which we insert items at the top and retrieve those items in last-in,first-out order) One stack class template, become the bases for creating many stack classed (such as “stack of double,”stack of int,”stack of char,”stack of employee,”etc.) Creating class template stack

Cont… #ifndef STACK_H #define STACK_H Template Class Stack { Public: Stack(int=10);//default constructor (stack size 10) // destructor ~Stack() { delete[] stackPtr; //deallocate internal space for stack }// end ~stack destructor

Cont… Bool push(const T&);//push an element onto the stack Bool pop(T&); //Pop an element off the stack Bool isempty() const { return top == -1; }//end function is empty //determine whether stack is full

Cont… Bool isfull() const { return top==size-1; }//end function isfull Private; int size; //# of element in the stack int top;//location of the top element (-1 means empty) T *stackptr; //pointer to internal representation of the stack };

Cont… //constructor template Template Stack ::stack(int s) :Size(S>0?s:10),//validate size top(-1),//stack initially empty stackptr(new T[Size]) //allocate memory for elements { //empty body } //end stack constructor template

Cont… //push element onto stack; //if successful, return true;otherwise,return false Template Bool Stack ::push(const T &pushvalue) if (lisfull()) { stackPtr[ ++top ] = pushvalue://place item on stack

Cont… return true; // pop successful } //endif return false; //push unsuccessful }//end function template push // pop element off stack; //if successful, return true; otherwise,return false Template bool stack ::pop(T &popvalue)

Cont… { if (!isEmpty() ) { popvalue = stackptr [top--]; //remove item from stack return true; //pop successful } //end if Return false; // pop unsuccessful }//end function template pop #endif

Cont… Template //non type parameter elements Stack …… Templates and inheritance A class template can be derived from a class template specialization A class template can be derived from a nontemplate class. A class-template specialization can be derived from a class-templat

Containers and templates template A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows a great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference objects with similar properties to pointers). Containers replicate structures very commonly used in programming: dynamic arrays (vector), queues (queue), stacks (stack), heaps (priority queue), linked lists (list), trees (set), associative arrays (map)...

Cont… Many containers have several member functions in common, and share functionalities. The decision of which type of container to use for a specific need does not generally depend only on the functionality offered by the container, but also on the efficiency of some of its members (complexity). This is especially true for sequence containers, which offer different trade-offs in complexity between inserting/removing elements and accessing them. stack, queue and priority queue are implemented as container adaptors. Container adaptors are not full container classes, but classes that provide a specific interface relying on an object of one of the container classes (such list) to handle the elements. The underlying container is encapsulated in such a way that its elements are accessed by the members of the container adaptor independently of the underlying container class used.

Cont… Container class templates Sequence containers: arrray Array class (class template )vactorVector (class template ) Double ended queue (class template )forward list Forward list (class template ) list List (class template )

Cont… Container adaptors: stackLIFO stack (class template )queueFIFO queue (class template )priority_queuePriority queue (class template ) Associative containers: setSet (class template )multisetMultiple-key set (class template )mapMap (class template )multimapMultiple-key map (class template ) Unordered associative containers: unordered_set Unordered Set (class template )unordered_multiset Unordered Multiset (class template )unordered_map Unordered Map (class template )unordered_multimap Unordered Multimap (class template ) stackqueuepriority_queue setmultisetmapmultimap unordered_set unordered_multiset unordered_map unordered_multimap

Revision Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one. Templates are very useful when implementing generic constructs like vectors, stacks, lists, queues which can be used with any arbitrary type C++ templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code. There are two kinds of templates: function templates and class templates Use function templates to write generic functions that can be used with arbitrary types. For example, one can write searching and sorting routines which can be used with any arbitrary type. The Standard Template Library generic algorithms have been implemented as function templates, and the containers have been implemented as class templates

Cont… Function templates A function template behaves like a function except that the template can have arguments of many different types In other words; a function template represents a family of functions. The general format of a function template is as follows: template return type functionname(argument of type T ) { // body of function with Type T } The following example declares a function template max(x, y) which returns either x or y, whichever is larger template myType max (myType a, myType b) { return (a>b?a:b);} The above definition of function max() can work with different kinds of data types. A function template does not occupy space in memory. The actual definition of a function template is generated when the function is called with a specific data type. The function template does not save memory.

Cont… A class template provides a specification for generating classes based on parameters. Class templates are commonly used to implement containers. A class template is instantiated by passing a given set of types to it as template arguments. The C++ Standard Library contains many class templates, in particular the containers adapted from the Standard Template Library, such as vector.

Template specialization It is possible to define a different implementation for a template when a specific type is passed as template argument. This is called a template specialization. For example, let's suppose that we have a very simple class called mycontainer that can store one element of any type and that has just one member function called increase, which increases its value. But we find that when it stores an element of type char it would be more convenient to have a completely different implementation with a function memberuppercase,