Motivation for Generic Programming in C++

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.
. 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.
Templates. Example… A useful routine to have is void swap(int &a, int &b){ int tmp = a; a = b; b = tmp; }
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++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
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.
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.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Templates ~ their instantiation and specialization.
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)‏
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
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
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)
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.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Chapter 2 Objects and Classes
CS212: Object Oriented Analysis and Design
Chapter 12 Classes and Abstraction
Pointers and Dynamic Arrays
Memory Management with Classes
How to be generic Lecture 10
C++ Templates.
Motivation and Overview
Chapter 14 Templates C++ How to Program, 8/e
Review: Two Programming Paradigms
classes and objects review
Chapter 5 Classes.
Pointers and Pointer-Based Strings
CS212: Object Oriented Analysis and Design
Generic Programming Techniques in C++
Starting Out with C++ Early Objects Eighth Edition
Templates.
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
The C++ Algorithm Libraries
Chapter 2 Objects and Classes
Object-Oriented Programming (OOP) Lecture No. 32
ADT Implementations: Templates and Standard Containers
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
CMSC 202 Lesson 22 Templates I.
Lists - I The List ADT.
Lists - I The List ADT.
7 Arrays.
Lecture 8-2 : STL Iterators and Algorithms
Overview of C++ Polymorphism
Pointers and Pointer-Based Strings
Templates I CMSC 202.
Data Structures and Algorithms Introduction to Pointers
Java Programming Language
CS410 – Software Engineering Lecture #5: C++ Basics III
Lists CMSC 202, Version 4/02.
Lists CMSC 202, Version 4/02.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
C++ Object Oriented 1.
Presentation transcript:

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

C++ STL Generic Programming Example #include <iostream> #include <iterator> #include <algorithm> 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 0 1 2 3 4 5 6 7 8 9 (ascending sort) sort (numbers, numbers + array_dimension); copy (numbers, numbers + array_dimension, ostream_iterator<int>(cout, " ")); cout << endl; // prints out 9 8 7 6 5 4 3 2 1 0 (descending sort) sort (numbers, numbers + array_dimension, greater<int>()); // prints out 5 6 2 1 9 4 7 8 3 0 (shuffled) random_shuffle (numbers, numbers + array_dimension); return 0; } native iterator type (pointer) user-defined iterator type native container type (array) calls to STL algorithms user-defined functor constructor calls

Decoupling Data Types from Algorithms 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 Functors plug in functions to modify algorithms Containers include arrays, vector, list, set Iterators include pointers, ostream_iterator Algorithms include sort, copy, random_shuffle Functors include less, greater

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) Functors decouple algorithms from their 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 functor be plugged in to produce a descending order

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

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<int> intlist; list<string> 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

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<int> v; Some compilers require that template definitions be included with declarations

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; 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

Another Function Template Example STL-style 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)

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.)

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