Generic programming – Function template

Slides:



Advertisements
Similar presentations
Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these.
Advertisements

Template. 2 Using templates, it is possible to create generic functions and classes. In a generic function or class, the type of data upon which the function.
TEMPLATES Lecture Presented By SHERY KHAN Object Orienting Programming.
1 Templates Chapter What You Will Learn Using function templates to created a group of overloaded functions Using class templates to create a group.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction.
1 Lecture 8: Introduction to C++ Templates and Exceptions  C++ Function Templates  C++ Class Templates.
Templates Overload function: define more than one function With same function name Different parameter type Different type Different number of parameter.
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.
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
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.
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.
1 Chapter 17-1 Templates and Exceptions Dale/Weems.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Operator Overloading. Introduction It is one of the important features of C++ language  Compile time polymorphism. Using overloading feature, we can.
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.
CS212: Object Oriented Analysis and Design
1 CSC241: Object Oriented Programming Lecture No 25.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Copyright 2006, The Ohio State University Introduction to C++ Templates l C++ Function Templates l C++ Class Templates.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 14: Overloading and Templates Overloading will not be covered.
Function Overloading and References
Chapter -6 Polymorphism
1 Chapter 17 Templates and Exceptions Dale/Weems.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
1 Advanced Topics in Functions Lecture Unitary Scope Resolution Operator Unary scope resolution operator ( :: )  Access global variable if.
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.
LECTURE LECTURE 17 Templates 19 An abstract recipe for producing concrete code.
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Programming Fundamentals Enumerations and Functions.
Welcome to FUNCTION OVERLOADING Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS) KV jhagrakhand.
Introduction to C++ Templates and Exceptions C++ Function Templates C++ Class Templates Exception and Exception Handler.
MAITRAYEE MUKERJI Object Oriented Programming in C++
Chapter 15 - C++ As A "Better C"
Motivation for Generic Programming in C++
Programming with ANSI C ++
User-Written Functions
C++ Templates.
Introduction to C++ Systems Programming.
FUNCTIONS In C++.
Exceptions, Templates, and the Standard Template Library (STL)
Chapter 14 Templates C++ How to Program, 8/e
Introduction to Custom Templates
This technique is Called “Divide and Conquer”.
CS212: Object Oriented Analysis and Design
Starting Out with C++ Early Objects Eighth Edition
Templates.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Name: Rubaisha Rajpoot
Functions.
Miscellaneous C++ Topics
Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Exception Handling.
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Function Templates Class Templates
Lecture 8: Introduction to C++ Templates and Exceptions
More C++ Concepts Exception Handling Templates.
Arrays.
Presentation transcript:

Generic programming – Function template

It is a 20 Jigsaw Puzzle Blank Template

Justify the statement phrase “Do not re-invent the wheel”

Example-1

Conventional Approach void printInt( int n ) { cout << “The Value is " << n ; } void printChar( char ch ) cout << “The Value is " << ch ; void printFloat( float x ) cout<<“The value is”<<x; void printDouble( double d ) cout<<“The value is”<<d; To output the traced values, we insert: printInt(sum); printChar(initial); printFloat(angle);

Function overloading Approach void Print( int n ) { cout << “The Value is " << n ; } void Print( char ch ) cout << “The Value is " << ch ; void Print( float x ) cout<<“The value is”<<x; void Print( double d ) cout<<“The value is”<<d; To output the traced values, we insert: Print(someInt); Print(someChar); Print(someFloat);

Generic function Approach   template<class SomeType> void Print( SomeType val ) { cout << “The value is " << val ; } Template parameter (class, user defined type, built-in types) To output the traced values, we insert: To output the traced values, we insert: Template argument Print<int>(sum); Print<char>(initial); Print<float>(angle);

What do you infer from the 3 approaches?? Compare all those approaches.

Approach-1(Conventional) Create separate functions with unique names for each combination of data types Difficult to keep track of multiple function names Approach-2(Function overloading) Eliminates the need to come up with many different names for identical tasks. Approach-3(Generic function) When the compiler instantiates a template, it substitutes the template argument for the template parameter throughout the function template.

Conventional Approach Summary of Three Approaches Conventional Approach Different Function Definitions Different Function Names Function Overloading Different Function Definitions Same Function Name Template Functions One Function Definition (a function template) Compiler Generates Individual Functions

Example-2 How to perform the swapping on different data items?

The above program performs well and is producing the output as well. But it is less efficient. Because the same function “swap” is redefined by multiple times. How to increase the efficiency of the above program?

Templates Template is a kind of macro that supports the generic programming which allows to develop the reusable components. It is one of the main features of object oriented language such as C++. Actually, it allows the declaration of data items without specifying their exact data type. Two types: 1.Function template 2.Class template

Need of Function Templates Reusability Avoids the redefinition of function. Describes a function format that when instantiated with particulars generates a function definition. Write once, use multiple times

Function Templates Function templates are generic functions, which can operate on different data items. C++ allows compiler to generate multiple versions of a function by allowing parameterized data types and hence it supports the parameterized polymorphism. Data items are not declared while defining function. When the function call is made using appropriate data type, then the template function is transformed to operate on that specific data types.

Function Templates For example, if we want to invoke the function swap(), so we just supply the required data type parameters to it and the compiler automatically invokes the function template by defining the appropriate data items. Therefore it allows a single “swap” with generic data type “T” to deal with multiple swap functions.

General syntax for function template: The syntax of the function template is similar to normal function definition template<class type> returntype functionname(arguments) { ………….. statements; ………. }

Guidelines to use the function template No argument template function template<class T> T fun() //Error: T is not used as an argument { return n; } Template type argument unused void test(int x) //Error: T is not used as an argument T temp; ------

3.Usage of partial number of template arguments template<class T, class U> void fun(T &x) //Error: U is not used as an argument { U temp; ------ }

Overloaded Function Templates The function template can also be overloaded with multiple declarations. As similar to function overloading, the overloaded function templates must differ interms of number of parameters or their type.

Declaration of a function template for functions having multiple parameters of different types requires multiple generic arguments or template arguments

Example Program

How to use multiple parameters in function template??

---continued In main(), the statement assign_B(50,10.15,s2); leads to compilation errors. Since, the above program is neither having the normal function nor function template ,atching with its parameters data type. Therefore, the solution to the problem encountered in the above program is to declare the second template function in the above program as follows:

--continued The declaration of the function template is the same, except that it has an extra argument in the template-argument-list, i.e class U. This declaration informs the compiler that template function assign_B() with two arguments should be instantiated. The compiler calls the appropriate instantiation. Any number of generic data types can be declared, provided all these generic data types are used in declaring formal parameters.

How to call the function template using user defined type

In Lab Practice problem In a library, the books are arranged vertically in the rack, one above the other. The book(s) can be added or removed only from the top and not in the middle. You have been assigned to add 10 books and remove the books until the book rack is empty. Develop the program using generic function.