Overview of C++ Templates

Slides:



Advertisements
Similar presentations
Object Oriented Programming
Advertisements

Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
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.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates.
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.
CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
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 
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
 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.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
Templates Overload function: define more than one function With same function name Different parameter type Different type Different number of parameter.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
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.
Templates and the STL.
CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers ( int ) vs. intervals ( pair )
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
EEL 3801 Part VIII Fundamentals of C and C++ Programming Template Functions and Classes.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers (long) or intervals (long, long)‏
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
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.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 16: Exceptions,
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
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.
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
CS212: Object Oriented Analysis and Design
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
1 CSE Programming in C++. 2 Overview Sign roster list Syllabus and Course Policies Introduction to C++ About Lab 1 Fill Questionnaire.
Overview of C++ Polymorphism
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.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
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.
MAITRAYEE MUKERJI Object Oriented Programming in C++
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Chapter 2 Objects and Classes
Motivation for Generic Programming in C++
Introduction to Generic Programming in C++
C++ Templates.
CS212: Object Oriented Analysis and Design
Templates.
CMSC 202 Lesson 22 Templates I.
Introduction to Programming
Overview of C++ Polymorphism
Templates I CMSC 202.
Presentation transcript:

Overview of C++ Templates Templates are used to parameterize classes and functions with different types Function templates do not require explicit declaration of the parameterized types when called Classes require explicit declaration of parameterized types when instantiated Some compilers require that template definitions be included with declarations – others do not

Function Templates template <typename T> void swap(T & lhs, T & rhs) { T temp = lhs; lhs = rhs; rhs = temp; } int main () { int i = 3; int j = 7; swap (i, j); // i is now 7, j is now 3 return 0; Function template swap takes a single type parameter, T interchanges values of two passed arguments of the parameterized type Compiler instantiates the function template with type int in main Note that the compiler infers that the type is int when swap is called Based on the types of the arguments i and j

Function Template Example STL linear search (based on Austern pp. 13): template <typename Iterator, typename T> Iterator find2 (Iterator first, Iterator last, const T & value) { while (first != last && *first != value) { ++first; } return first; Our first generic algorithm Searches any one-dimensional sequence of elements “Not found” is a normal result, does not throw exception Returns position last: just past the end of the range [first, last)

More about Concepts and Models A concept defines type requirements A predicate to classify/categorize types Any specific type that meets the requirements is a model of that concept What requirement(s) does the expression return first; impose? What about while(first != last && *first != value) { ++first; } Iterator const T &

Interface Polymorphism: Refinement A concept C is a refinement of concept D if C imposes all of the requirements of D Modeling and refinement satisfy three formal properties Reflexivity: A concept refines itself Containment: if T models C and C refines D then T models D Transitivity: If C refines D then C refines any concept D refines What in the OO paradigm is this like? How does it differ? C0 transitivity C1 T1 T2 C2 containment T3 T4 can substitute, e.g., T3 for T1

Class Templates Start with a simple declaration template <typename T> class Array { public: Array(const int size); ~Array(); const int size () const; private: T * m_values; const int m_size; }; int main (int, char**) { Array <int> a(10); return 0; } Start with a simple declaration Which we’ll expand as we go Notice that parameterized type T is used within the class template Type of pointer to array When an instance is declared, must also explicitly specify the concrete type parameter E.g., int in function main (int, char**)

Class Templates and Inheritance class ArrayBase { public: ArrayBase(const int size); ~ArrayBase(); const int size () const; protected: const int m_size; }; template <typename T> class Array : public ArrayBase { Array(const int size); ~Array(); private: T * m_values; Class templates can inherit from base classes Or class templates, but must relate type parameters to those of base Here, we’ve separated template and non-template code Non-template base class Template derived class Functions and variables that do not need to refer to type parameters go into the base class This is useful in many cases To avoid accidental type errors (ArrayBase doesn’t access T) To reduce program size (separate method definitions compiled for Array<int> Array<float> etc.)

One Last Detail: Associated Types template <typename T> class Array : public ArrayBase { public: typedef T* iterator; Array(const int size); ~Array(); iterator begin () { return m_values;} iterator end () { return m_values+m_size;} private: T * m_values; }; void foo { Array<int> a; fill_array(a); for (Array<int>::iterator i = a.begin(); i != a.end(); ++i) { cout << *i << “ ” << endl; } The exact type of a type parameter is not known The compiler can work around that in many cases But sometimes it needs more information Additional information can be associated with a type For example, a class template can define an iterator type Available to the template and code that uses the template More about how this is done (and why) in later lectures

Tips on Templates The set of requirements that a class template or function template places on its parameterized types is called a concept in generic programming terminology Any type that meets those requirements is said to model the concept, and can be used in that template Concept refinement supports interface polymorphism Push common code and variables up into non-template base classes Can help avoid subtle type errors Can help reduce the size of the executable program Associated types expand the power of templates E.g., used extensively in the C++ Standard Template Library

For Next Time Topic No assigned readings Template Examples Please catch up if you’ve not done so already