Templates L. Grewe. 2 Goals Often want to do basically the same thing w/diff things –functions work on variables only types specified –  algorithmic.

Slides:



Advertisements
Similar presentations
Introduction to C++ Templates Speaker: Bill Chapman, C++ developer, financial company in Mid-Manhattan. Can be reached via: ' This.
Advertisements

THE PREPROCESSOR. Preprocessing is (apparently) done before actual compilation begins. The preprocessor doesnt know (very much) C. Major kinds of preprocessor.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates.
Templates in C++. Generic Programming Programming/developing algorithms with the abstraction of types The uses of the abstract type define the necessary.
TEMPLATES Lecture Presented By SHERY KHAN Object Orienting Programming.
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.
C/c++ 4 Yeting Ge.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 23 : Generics King Fahd University of Petroleum & Minerals College of Computer Science.
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.
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.
 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.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
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.
(…A FEW OF THEM) C++ DESIGN PATTERNS. WHAT ARE THEY? Commonly occurring constructs Could be part of good software engineering Not universally agreed Good.
Review for Midterm Chapter 1-9 CSc 212 Data Structures.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Recap, Test 1 prep, Composition and Inheritance. Dates Test 1 – 12 th of March Assignment 1 – 20 th of March.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
Templates An introduction. Simple Template Functions template T max(T x, T y) { if (x > y) { return x; } else { return y; } } int main(void) { int x =
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
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.
1 CSC241: Object Oriented Programming Lecture No 25.
#include guards Practical session #2 Software Engineering
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Overview of C++ Templates
Generic lists Vassilis Athitsos. Problems With Textbook Interface? Suppose that we fix the first problem, and we can have multiple stacks. Can we have.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
Compiler Directives. The C Preprocessor u The C preprocessor (cpp) changes your source code based on instructions, or preprocessor directives, embedded.
Weekly C-minar Week 0. Today: Steps of the compile Basic inclusion/syntax rules Low-cost containment Debugging.
Computer Science and Software Engineering University of Wisconsin - Platteville 5. Template Yan Shi CS/SE 2630 Lecture Notes.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
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.
Object Oriented Programming COP3330 / CGS5409.  Class Templates  Bitwise Operators.
C++ Templates 1. Why Use Templates? C++ requires variables, functions, classes etc with specific data types. However, many algorithms (quicksort for example)
ENEE150 – 0102 ANDREW GOFFIN Abstract Data Types.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
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.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
C++ REVIEW – TEMPLATES. GENERIC PROGRAMMING Programming/developing algorithms with the abstraction of types Algorithms/data is expressed “without type”
Programming with ANSI C ++
How to be generic Lecture 10
Templates.
FUNCTIONS In C++.
Functions Separate Compilation
Templates.
Templates in C++.
Templates ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY.
CMSC 202 Templates.
Register Variables Declaring a variable as a "register" variable is an advisory to the compiler to keep the normal location of the variable in a register,
Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
CS2011 Introduction to Programming I Methods (II)
Exception Handling.
Template Functions Lecture 9 Fri, Feb 9, 2007.
Parasol Lab, Texas A&M University
Yan Shi CS/SE 2630 Lecture Notes
Template.
Templates An introduction.
Templates CMSC 202, Version 4/02.
COP 3330 Object-oriented Programming in C++
Presentation transcript:

Templates L. Grewe

2 Goals Often want to do basically the same thing w/diff things –functions work on variables only types specified –  algorithmic thinking –  computer science –  “functionalism” in phil. of mind –  abstraction Sometimes want to do basically the same thing with different types of things –LL of ints, LL of widgets –“abstract data types”

3 Goals Suppose want the max of two numbers What kind of numbers? –ints –chars –floats –doubles All! How?

4 Max with typedef Suppose want the max of two numbers What kind of numbers? ints chars floats doubles All! How? typedef... dtype; dtype max(dtype a, dtype b) { return a > b ? a : b; } typedef... dtype; dtype max(dtype a, dtype b) { return a > b ? a : b; }

5 max function Soln 1: Write one function for each type, e.g.: Is allowed in C++ (“overloading”) But this is manually duplicating code –for nontrivial ftns – very bad –hard to maintain! int max(int a, int b) { return a > b ? a : b; } double max( … int max(int a, int b) { return a > b ? a : b; } double max( …

6 max functions Soln 2: Write one, maxly general function This works but it’s not nice –All four types can widen to doubles –but must be cast back double max(double a, double b) { return a > b ? a : b; } double x = max(2.5, 3.5); char c = (char)max('A','B'); double max(double a, double b) { return a > b ? a : b; } double x = max(2.5, 3.5); char c = (char)max('A','B');

7 max functions Soln 3: Use the C++ preprocessor macros C++ source code is preprocessed –#includes replaced with header files –#ifndef, etc. –macro calls replaced with macro content  Works too, but complications, e.g.: –  –x, y inc-ed twice Need many parentheses – sq(a+b), etc. #define max(a,b) (a > b ? a : b) int c = max(2,3); int c = (2 > 3 ? 2 : 3); z = max(x++, y++) z = (x++ > y++ ? x++ : y++)

8 max functions Soln 4: Use the CPP in a more sophisticated way Don’t use the CPP to generate expressions but to generate functions, e.g.: Avoids the previous CPP problems But reqs code for all poss types –Done partly manually –Increases executable size #define define_max(t)\ t max(t a, t b) {\ return a > b ? a : b; \ } define_max(char) define_max(int) #define define_max(t)\ t max(t a, t b) {\ return a > b ? a : b; \ } define_max(char) define_max(int)

9 Templates –T is a place-holder for the substituted type –template and class are both keywords T is some type –Primitive, class, array, etc. –All occurrences of T in ftn replaced with the real type used in particular case template result ftn(param-list) {…}

10 max functions Soln 5: use templates –parameterized function –expands per type as necessary Now can simply call the function: – Compiler automatically creates only the function specializations needed template T max(T a, T b) { return a > b ? a : b; } template T max(T a, T b) { return a > b ? a : b; } x = max(2.5,3.5);

11 Templates: swapping How to swap two ints? Suppose we want to swap other types  templates void swap(int &a, int &b) { int c = a; a = b; b = c; } void swap(int &a, int &b) { int c = a; a = b; b = c; }

12 Generic swapping Now can swap any prim Can also swap any objects –As long as = op is public and works correctly! template void swap(T &a, T &b) { T c = a; a = b; b = c; } template void swap(T &a, T &b) { T c = a; a = b; b = c; }

13 Template specialization string s,t … max(s,t); works But max("hi","there") doesn’t: if ("hi" < "there") … compares two pointers - where the char[] s start –Not what we mean Solution: create a specialization –special version for this case –We check for spec. before template char *max(char *a, char *b) { return strcmp(a,b) > 0 ? a : b; } char *max(char *a, char *b) { return strcmp(a,b) > 0 ? a : b; }

14 Template Classes Not just Templates for functions but, also classes. Define How to use it? Consider a node class defined with templates. node * age = NULL; ages.set(18); node name; name.set("Jorge"); node *grid; grid = new node ; grid->set(point(2,4)); Consider a node class defined with templates. node * age = NULL; ages.set(18); node name; name.set("Jorge"); node *grid; grid = new node ; grid->set(point(2,4)); Template class node { T value; //member functions template T node ::set(T v){ value= v; } } Template class node { T value; //member functions template T node ::set(T v){ value= v; } }

15 What to know about templates Template Function –a template prefix before the function implementation –template Function Prototype –a template prefix before the function prototypes Template Class –a template prefix right before the class definition Instantiation –template functions/classes are instantiated when used\