Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }

Slides:



Advertisements
Similar presentations
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Advertisements

Overloading Operators Overloading operators Unary operators Binary operators Member, non-member operators Friend functions and classes Function templates.
CMSC 202, Version 2/02 1 Operator Overloading Strong Suggestion: Go over the Array class example in Section 8.8 of your text. (You may ignore the Array.
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)
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
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; }
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
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.
Chapter 15: Operator 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.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
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’
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 14: Overloading and Templates.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
Templates. Before we dive in 2 Preprocessing Compilation Linkage.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
ECE122 Feb. 22, Any question on Vehicle sample code?
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
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.
Overview of C++ Templates
Chapter 3 Templates Saurav Karmakar Spring Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Chapter 13: Overloading and Templates. Objectives In this chapter, you will – Learn about overloading – Become familiar with the restrictions on operator.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
Copyright © 2009 – Curt Hill Standard Template Library An Introduction.
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.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
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.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
MAITRAYEE MUKERJI Object Oriented Programming in C++
Chapter 2 Objects and Classes
CSE1002 – Problem Solving with Object Oriented Programming
Motivation for Generic Programming in C++
Chapter 13: Overloading and Templates
C++ Templates.
Templates.
Introduction to C++ Systems Programming.
Introduction to Classes
Chapter 15: Overloading and Templates
Templates.
ADT Implementations: Templates and Standard Containers
Introduction to Classes
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Templates

Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }

Example… What happens if we want to swap a different type such as double and string ? For each one, we need different function, code duplication a known bug recipe! void swap( double& a, double &b ) { double tmp = a; a = b; b = tmp; } void swap( string& a, string &b ) { string tmp = a; a = b; b = tmp; }

Generic Programming All these versions of swap are “isomorphic” // template code for swap for arbitrary type T void Swap( T &a, T &b ) { T tmp = a; a = b; b = tmp; } Can we somehow tell the compiler to use swap with any type T ?

Templates The template keyword defines “templates” Piece of code that will be regenerated with different arguments each time. template // T is a “type argument” void swap(T& a, T &b) { T tmp = a; a = b; b = tmp; }

Template Instantiation int main() { int a = 2; int b = 3; swap(a, b);//requires swap(int&, int&) } The compiler encounters swap(int&, int&) It instantiates the template swap with T = int and compiles the code defined by it. Same as: swap (a,b);

Template Instantiation Different instantiations of a template can be generated by the same program. Swap example swap.cppswap.cpp

Templates & Compilation A template is a declaration. The compiler performs syntax checks only. When a template is instantiated with specific arguments, then the generated code is compiled Implications: Template code has to be visible by the code that uses it (i.e., appear in.h file). Compilation errors can occur only in a specific instance (see swap.cpp).swap.cpp

Another Example… // Inefficient generic sort… template void sort( T* begin, T* end ) { for( ; begin != end; begin++ ) for( T* q = begin+1; q != end; q++ ) if( *q < *begin ) swap( *q, *begin ); } See [Sort.h, TestSort.cpp]Sort.hTestSort.cpp

More Complex Case… Suppose we want to avoid writing operator != for new classes. template bool operator!= (T const& lhs, T const& rhs) { return !(lhs == rhs); } When is this template used?

More Complex Case… class MyClass { public: … bool operator==(MyClass const & rhs) const; … }; … int a, b; … if( a != b ) // uses built in operator!=(int,int) … MyClass x,y; if( x != y ) // uses template with T = MyClass …

When Templates are Used? Resolution When the compiler encounters … f( a, b ) … Search for a function f() with matching type signature. If not found, search for a template function that can be instantiated with matching types.

Generic Classes? Suppose we implement a class StrList that maintains a list of strings. –See StrList.h and StrList.cppStrList.h StrList.cpp The actual code for maintaining the list has nothing to do with the particulars of the string type Can we have a generic implementation of lists?

Class Templates template class MyList { … }; … MyList intList; // T = int MyList stringList; // T = string

Class Templates Code similar to usual code: Add template statement before each top-level construct. Use template argument as type in class definition. Implementation of methods, somewhat more complex syntax. –See MyList.h TestMyList.hMyList.h TestMyList.h

Iterators

Constructing a List We want to initialize a list from an array. We can write a method that receives a pointer to the array, and a size argument int array[] = { 1, 2, 3, 4, 5, 6 }; MyList list; list.copy( array, 6 ); Alternative: use a pointer to initial position and one to the position after the last list.copy( array, array+6 ); This form is more flexible (as we shall see)

Constructing a List // Fancy copy from array template MyList ::copy( T const* begin, T const* end ) { T const* p; for( p = begin; p != end; p++ ) pushBack(*p); }

Pointer Paradigm C/C++ idiom : T * p; for( p = begin; p != end; p++ ) { // Do something with *p } Applies to all elements in [begin,end-1] Common in C/C++ programs Can we extend it to other containers?

Iterator Object that behaves just like a pointer. Allows to iterate over elements of a container. Example: MyList L; … MyList ::iterator i; for( i = L.begin(); i != L.end(); i++ ) cout << " " << *i << "\n";

Iterators To emulate pointers, we need: copy constructor for function call. operator = for assignments. operator == comparing two pointers. operator * for accessing a value operator++ for pointer arithmetic.

MyList iterator Keep a pointer to a node class iterator { … private: Node m_pointer; }; Provide encapsulation, since through such an iterator we cannot change the structure of the list See MyListWithIterators.hMyListWithIterators.h

Side Note operator++ In C we can use ++ in two forms: prefix notation ++x –increment x –fetch x ’s value postfix notation x++ –fetch x ’s value –increment x How can we implement both variants?

Operator++ Prefix form: T& T::operator++(); Postfix form T T::operator++(int); // dummy argument! Note different return types See MyListWithIterators.hMyListWithIterators.h

Initializing a List We now want to initialize a list from using parts of another list Something like template MyList ::copy( iterator begin, iterator end ) { iterator p; for( p = begin; p != end; p++ ) pushBack(*p); }

Generic Constructor The code for copying using –T* –MyList ::iterator are essentially identical –on purpose --- iterators mimic pointers Can we write the code once?

Template within a template template class MyList { … template copy( Iterator begin, Iterator end ) { for( Iterator p = begin; p != end; p++ ) pushBack(*p); } … };

Copy Method MyList ::copy() can be instantiated with different types –pointer to T –MyList ::iterator –Iterators of other data structures that contain objects of type T

Template Variations Can receive constant arguments template class Buffer { … private: T m_values[Size]; }; … Buffer Buff1; Buffer Buff2; // same as Buff1 Buffer Buff3;

Template and Types Buffer is not a type Buffer is a type Buffer, buffer are two names for the same type Buffer is a different type

Class Templates - Recap Provides support for generic programming Parameters are either types or constants. Default values can be specified. Depends only on the properties it uses from its parameter types. Resulting classes may be very efficient, but code size may be larger. Difficult to write, maintain and debug. Class template overloading is impossible.

Summary Use templates to express algorithms that apply to many argument types. Use template to express containers. Alternative mechanism to polymorphism. Write & Debug concrete example before generalizing to a template Understand iterators and other “helper” classes Foundation for C++ standard library (STL)

Things to read about Standard Library – implementation of string - algorithms (sort, swap, etc.) - relational operators