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.

Slides:



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

CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
CSE 332: C++ copy control I Copy Control (Part I) Copy control consists of 5 distinct operations –A copy constructor initializes an object by duplicating.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Chapter 14: Overloading and Templates
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
. 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 81 Object Oriented Programming Spring 2007 Recitation 8.
C++ for Engineers and Scientists Third Edition
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,
Basic C++ Sequential Container Features
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
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.
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 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
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.
Data Structures Using C++ 2E
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Templates ~ their instantiation and specialization.
CSE 425: Data Types II Survey of Common Types I Records –E.g., structs in C++ –If elements are named, a record is projected into its fields (e.g., via.
CS 11 C++ track: lecture 7 Today: Templates!. Templates: motivation (1) Lots of code is generic over some type Container data types: List of integers,
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)‏
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
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”
Overview of C++ Templates
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
CSE 332: Memory management with C++ classes Memory Management with Classes Review: for non-static built-in (native) types –default constructor and destructor.
Computing and Statistical Data Analysis Lecture 6 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Introduction to classes and objects:
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
1 CS Programming Languages Class 22 November 14, 2000.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Overview of C++ Polymorphism
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)
Classes: Defining Your Own Data Types Basic principles in OOP Define a new data type as a class and use objects of a class Member Functions –Constructors.
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 –
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
Chapter 2 Objects and Classes
Motivation for Generic Programming in C++
C++ Templates.
Motivation and Overview
Pointers and Pointer-Based Strings
Generic Programming Techniques in C++
Starting Out with C++ Early Objects Eighth Edition
Templates.
The C++ Algorithm Libraries
CMSC 202 Lesson 22 Templates I.
Overview of C++ Polymorphism
Pointers and Pointer-Based Strings
Templates I CMSC 202.
Java Programming Language
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

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 it into functions We’ve also looked at object-oriented programming –Reuse of code and data by packaging them into classes However, these techniques alone have limitations –Functions are still specific to the types they manipulate E.g., swap (int, int) and swap (int *, int *) do essentially same thing But, we must write two versions of swap to implement both –Classes alone are still specific to the types they contain E.g., keep an array (not a vector) of dice and an array of players –Must write similar data structures and code repeatedly E.g., adding a new element to an array Generic programming aims to relieve these limitations

CSE 332: C++ templates and generic programming I C++ STL Generic Programming Example #include using namespace std; int main (int, const char **) { int numbers [] = {0, 9, 2, 7, 4, 5, 6, 3, 8, 1}; size_t array_dimension = sizeof (numbers) / sizeof (int); // prints out (ascending sort) sort (numbers, numbers + array_dimension); copy (numbers, numbers + array_dimension, ostream_iterator (cout, " ")); cout << endl; // prints out (descending sort) sort (numbers, numbers + array_dimension, greater ()); copy (numbers, numbers + array_dimension, ostream_iterator (cout, " ")); cout << endl; // prints out (shuffled) random_shuffle (numbers, numbers + array_dimension); copy (numbers, numbers + array_dimension, ostream_iterator (cout, " ")); cout << endl; return 0; } native container type (array) callable object native iterator type (pointer) user-defined iterator type calls to STL algorithms Iterator constructor calls

CSE 332: C++ templates and generic programming I Decoupling Data Types from Algorithms The C++ STL has an architectural separation of concerns –Containers hold data of a particular type –Iterators give access to ranges of data –Algorithms operate on particular kinds of iterators –Callable objects plug in functions to modify algorithms Containers include arrays, vector, list, set Iterators include pointers, ostream_iterator Algorithms include sort, copy, random_shuffle Callable objects include less, greater

CSE 332: C++ templates and generic programming I Decoupling Data Types from Algorithms (cont.) Iterators decouple algorithms from containers –Algorithms require specific iterator interfaces –Containers provide iterators that give specific interfaces –Allows safe combinations, disallows unsafe/inefficient ones E.g., algorithm can use ++ for iterator over linked list or array E.g., algorithm can only use [ ] or += for iterator over array (not list) Callable objects decouple algorithms’ sub-steps –E.g., algorithms like sort use a comparison function –Sorting is valid for a variety of different comparisons And may give different results for each of them –Allowing different comparison functions to be plugged in Lets the sort default to producing an ascending order Lets a different callable be plugged in to produce a descending order

CSE 332: C++ templates and generic programming I Supporting Native and User Defined Types Native arrays provide a natural container abstraction –Hold a (contiguous) range of elements –Can access the values at different positions –Can change the values at different positions –With pointers, new, and delete, can even re-dimension them Native pointers provide a natural iterator abstraction –Point to a position in a container (e.g., an array) –Can move from one position to the next (e.g., ++, +=) –Can be dereferenced to obtain the value at aliased location Since C++ STL can’t change how native types work –It uses arrays and pointers as a container/iterator example –It ensures that user-defined containers/iterators are similar –Pointers support all operations any STL iterator must provide

CSE 332: C++ templates and generic programming I Support for Generic Programming in C++ The power of C++ generics comes from 3 main ideas –Decoupling data types from algorithms operating on them –Seamlessly supporting both native and user defined types –Templates: type parameterization, interface polymorphism Templates introduce type parameterization –Allows you to write functions like swap once … … and then plug in parameter types as needed –Allows you to write class templates … … and then plug in member variable types later –This already allows a great deal of flexibility, e.g., list intlist; list stringlist; where list is a template, and int and string are used as type parameters to different instantiations of that template Templates introduce interface polymorphism –Templates impose type requirements on their parameters –Can plug in any types for which template’s syntax is valid

CSE 332: C++ templates and generic programming I Templates: Crucial to C++ Generic Programming Templates are used to parameterize classes and functions with different types –Function templates do not require explicit declaration of parameterized types when called E.g., swap (i, j); –Classes require explicit declaration of parameterized types when instantiated E.g., vector v; Some compilers require that template definitions be included with declarations

CSE 332: C++ templates and generic programming I Function Templates template void swap(T & lhs, T & rhs) { T temp = lhs; lhs = rhs; rhs = temp; } int main () { int i = 3; int j = 7; long r = 12; long s = 30; swap (i, j); // i is now 7, j is now 3 swap (r, s); // r is now 30, s is now 12 return 0; } The swap function template takes a single type parameter, T –interchanges values of two passed arguments of the parameterized type Compiler instantiates the function template twice in main –with type int for the first call –with type long for the second call –Note that the compiler infers the type each time swap is called –Based on the types of the arguments

CSE 332: C++ templates and generic programming I Another Function Template Example STL-style linear search (based on Austern pp. 13): template 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 )

CSE 332: C++ templates and generic programming I Class Templates template 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 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**)

CSE 332: C++ templates and generic programming I Class Templates and Inheritance class ArrayBase { public: ArrayBase(const int size); ~ArrayBase(); const int size () const; protected: const int m_size; }; template class Array : public ArrayBase { public: 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 Array etc.)

CSE 332: C++ templates and generic programming I Templates Introduce Interface Polymorphism Can plug in any types for which template’s syntactic use is valid (get a compiler error if not) –Templates apply to types that provide a common interface –What needs to be common depends on the template Templates impose requirements on type parameters –Each requirement consists of a C++ expression that must be valid for that types involved in that expression e.g., if a template’s code has Z z; Z must allow default construction Interface polymorphism still allows Liskov Substitution –If S models a subset of the requirements modeled by T then wherever you need an S you can plug in a T –Much more on this in the next several lectures