Templates & Generic Programming Junaed Sattar November 12, 2008 Lecture 10.

Slides:



Advertisements
Similar presentations
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
Advertisements

Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates.
Review What is a virtual function? What can be achieved with virtual functions? How to define a pure virtual function? What is an abstract class? Can a.
Chapter 17 Templates. Generic Algorithms Algorithms in which the actions or steps are defined, but the data types of the items being manipulated are not.
1 Templates Chapter What You Will Learn Using function templates to created a group of overloaded functions Using class templates to create a group.
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)
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
1 Random number generation Using srand(), rand() & time(0) Searching and Sorting Demo Making searching & sorting more generic Overloading the functions.
Introduction to Data Structure, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Standard Template Library Ming.
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.
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
 2006 Pearson Education, Inc. All rights reserved Generics.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 28P. 1Winter Quarter Inheritance and Overloading.
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.
Intro to Generic Programming Templates and Vectors.
Chapter 13. Binary Files In binary files we do not need to format data File streams include two member functions specifically designed to input and output.
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.
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.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
The Fundamentals of C++ Chapter 2: Basic programming elements and concepts JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Parameter Passing Mechanisms Reference Parameters Read § §
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Parameter Passing Mechanisms Reference Parameters § §
Dynamic memory allocation and Pointers Lecture 4.
Computer Programming & Applications Mohamed Iqbal Pallipurath Lecture 02P. 1 Inheritance and Overloading Lecture 28.
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.
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.
CS212: Object Oriented Analysis and Design
1 CSC241: Object Oriented Programming Lecture No 25.
Overview of C++ Templates
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
 Templates enable us to define generic classes and functions and thus provides support for generic programming. Generic types are used as parameters.
CS212: Object Oriented Analysis and Design Lecture 22: Generic Class Design.
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.
CSC1201: Programming Language 2 1 Functions. 2 Function declaration: return_type FuncName( Type arg1, Type arg2,….. Type argN) { function body } A program.
Lecture 17: 4/4/2003CS148 Spring CS148 Introduction to Programming II Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
Templates יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום רביעי 08 יוני 2016 יום.
 2006 Pearson Education, Inc. All rights reserved Templates.
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.
Motivation for Generic Programming in C++
Hightlights C++ Template C++ Number Systems.
C++ Templates.
Exceptions, Templates, and the Standard Template Library (STL)
Exceptions, Templates, and the Standard Template Library (STL)
CS212: Object Oriented Analysis and Design
Template Functions Chapter 6 introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation.
Template Functions Chapter 6 introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation.
Name: Rubaisha Rajpoot
Template Functions Chapter 6 introduces templates, which are a C++ feature that easily permits the reuse of existing code for new purposes. This presentation.
Exception Handling.
Standard Version of Starting Out with C++, 4th Edition
Exceptions, Templates, and the Standard Template Library (STL)
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Presentation transcript:

Templates & Generic Programming Junaed Sattar November 12, 2008 Lecture 10

Today Generic programming  templates  function templates  class templates  template specialization

Generic Programming Algorithms are written independently of data  data types are filled in during execution  functions or classes instantiated with data types  formally known as specialization Also used in Metaprogramming  used by a compiler to generate temporary source code

Compilation Stages? What steps from source to executable?  Source  Preprocess (C/C++ specific)  Compile  Link

Lets motivate ourselves Number of algorithms are data-type independent  sorting  searching  finding n-th largest  swapping etc Write once, use many times philosophy  dramatically reduces LOC (lines-of-code)  makes code much easier to maintain

In C++ Templates = generic programming Two types  function templates special functions that can operate with generic types.  class templates can have members that use template parameters as types

Function Templates special functions using template types. A template parameter is a special kind of parameter used to pass a type as argument  just like regular function parameters  but pass types to a function

Declaration Format? format for declaring function templates with type parameters template function_ declaration; Same functionality, different keywords  use older compilers only used format

Example create a template function that returns the greater one of two objects template myType GetMax (myType a, myType b) { return (a>b?a:b); }

Synopsis template keyword must appear before function or class templates followed by the list of generic or template types  can have more than one generic type... followed by function declaration and/or definition  template function uses myType as a type, not data

Usage int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax (i,j); n=GetMax (l,m); cout << k << endl; cout << n << endl; return 0; } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax(i,j); n=GetMax(l,m); cout << k << endl; cout << n << endl; return 0; }

Invalid Usage int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax(i,l); n=GetMax(j,m); } One template type only in definition  call mixes int and long types

Multiple template types define template types after the template keyword template myType GetMax (T1 a, T2 b) { return (a>b?a:b); } no difference in function call  programmer must ensure “sane” algorithm

Class templates classes can have members that use template parameters as type template class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } };

To use stores two elements of any valid type to store two integer values of type int with the values 115 and 36: mypair myobject (115, 36); to store two doubles: mypair mydubs (3.0, 2.18);

Non-inline definition to define a function member outside the declaration of the class template, always precede that definition with the template prefix template class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } T GetMax(); };

Continued template T mypair ::getmax () { T retval; retval = a>b? a : b; return retval; } int main () { mypair myobject (100, 75); cout << myobject.getmax(); return 0; }

Why so many T's?? There are three T's in this declaration first one is the template parameter. second T refers to the type returned by the function third T (the one between angle brackets) specifies that this function's template parameter is also the class template parameter.

Specialization Why and what?  to define a different implementation for a template when a specific type is passed as template parameter explicitly declare a specialization of that template

Sample Case A class with a sort method  sorts ints, chars, doubles, floats  also need to sort strings based on length, but the algorithm is different not lexicographic sorting Need to explicitly create template specialization for the sort method when string is passed as type

Code template class MyContainer { T element[100]; public: MyContainer( T *arg ){...}; void Sort() { // use your favorite sorting algorithm } };

Code // class template specialization: template <> class MyContainer { string element[100]; public: MyContainer (string *arg) {...} void Sort() { // use a string-length based sort here } };

Non-type parameters? templates can also have regular typed parameters, similar to those found in functions template class mysequence { T memblock [N]; public: void setmember (int x, T value); T getmember (int x); };

Continued template T mysequence ::getmember (int x) { return memblock[x]; } int main () { mysequence myints; mysequence myfloats; myints.setmember (0,100); myfloats.setmember (3,3.1416); cout << myints.getmember(0) << '\n'; cout << myfloats.getmember(3) << '\n'; return 0; }

Next Class STL Exceptions and namespaces