Generic Programming in C++. Generic Parameters Function for squaring a number: Function for squaring a number: sqrt(x) { return x * x; } C version: 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

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.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
C/c++ 4 Yeting Ge.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Templates and Polymorphism Generic functions and classes.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
 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; }
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as 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++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
Standard Template Library C++ introduced both object-oriented ideas, as well as templates to C Templates are ways to write general code around objects.
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.
Templates and Polymorphism Generic functions and classes
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
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
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)‏
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
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.
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.
CSC Data Structures, Fall, 2008 Monday, September 29, end of week 5, Generic Functions and Classes in C++
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
Overview of C++ Templates
CS212: Object Oriented Analysis and Design Lecture 28: Functors.
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
Concepts in C++. Templates in current C++ C++ template is typeless No language support for constrained generics Accidental errors found in instantiation.
C++ for Java Programmers Chapter 2. Fundamental Daty Types Timothy Budd.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
C++ Lecture 9 Tuesday, 26 Aug Templates l Template can be a class or function that has data types as parameters. The types are realized when the.
C:\Temp\Templates 4 5 Use This Main Program 6.
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
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.
Vectors Updated 11/4/2003 by Kip Irvine. Copyright Kip Irvine Overview What is a vector? Declaring vector objects Inserting and removing items Using.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
 2006 Pearson Education, Inc. All rights reserved Templates.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
Duke CPS Iterators: Patterns and STL l Access a container without knowing how it’s implemented ä libtapestry: first, isDone, next, current iterators.
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”
Generic Programming in C++ Giuseppe Attardi Università di Pisa.
Motivation for Generic Programming in C++
Standard Template Library
C++ Templates.
Operator overloading Conversions friend inline
OOP-4-Templates, ListType
C++ Templates L03 - Iterator 10 – Iterator.
C++ Functions, Classes, and Templates
Introduction to Programming
Abstraction: Generic Programming, pt. 2
Exceptions, Templates, and the Standard Template Library (STL)
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
Standard Template Library
Presentation transcript:

Generic Programming in C++

Generic Parameters Function for squaring a number: Function for squaring a number: sqrt(x) { return x * x; } C version: C version: int sqrt(int x) { return x * x; } Multiple versions: Multiple versions: int sqrtInt(int x) { return x * x; } C++ overloading: C++ overloading: int sqrt(int x) { return x * x; } double sqrt(double x) { return x * x; }

C++ Templates template template T sqrt(T x) { return x * x; } Compiler automatically generates a version for each parameter type used by a program: Compiler automatically generates a version for each parameter type used by a program: int a = 3; double b = 3.14; int aa = sqrt(a); double bb = sqrt(b);

Notes: macros’ limits #define sqrt(x) ((x) * (x)) int aa = sqrt(a++); int aa = ((a++) * (a++)); int aaa = sqrt(aa); #define fact(n) (n == 0) ? 1 : fact(n-1) * n #define SQRT(T) T sqrt(T x) {return x * x; } SQRT(int);SQRT(double);sqrt(a);sqrt(b);

Other types as well? class Complex { double real, imag; Complex operator *(Complex y) { return Complex( real * y.real – imag * y.imag, real * y.imag + imag * y.real); } Complex c(1, 2); Complex cc = sqrt(c);

Compile time checking template template void swap(T& a, T& b) { const T temp = a; a = b; b = temp; } int a = 5, b = 9; swap(a, b);// OK double c = 9.0; swap(a, c);// error

C++ Standard Template Library Goal: represent algorithms in as general form as possible without compromising efficiency Goal: represent algorithms in as general form as possible without compromising efficiency Extensive use of templates Extensive use of templates Only uses static binding (an inlining) Only uses static binding (an inlining) Use of iterators for decoupling algorithms from containers Use of iterators for decoupling algorithms from containers Iterator: abstraction of pointers Iterator: abstraction of pointers

STL Organization Containers Containers –vector, deque, list, set, map, … Algorithms Algorithms –for_each, find, transform, sort Iterators Iterators –forward_iterator, reverse_iterator, istream_iterator, … Function Objects Function Objects –plus, equal, logical_and, project1 Allocators Allocators

Examples from C++ Annotations vector vector inner_product inner_product sort sort

Forward Iterator int main(int argc, char **argv) { vector args(argv, argv + argc); vector args(argv, argv + argc); vector ::iterator iter = args.begin(); vector ::iterator iter = args.begin(); for ( ; iter != args.end(); ++iter ) for ( ; iter != args.end(); ++iter ) cout << *iter << " "; cout << endl; cout << endl;

Reverse Iterator vector ::reverse_iterator iter = args.rbegin(); vector ::reverse_iterator iter = args.rbegin(); for (; iter != args.rend(); ++iter ) for (; iter != args.rend(); ++iter ) cout << *iter << " "; cout << endl; cout << endl;

Inner Product unsigned ia1[] = {1, 2, 3, 4, 5, 6, 7}; unsigned ia2[] = {7, 6, 5, 4, 3, 2, 1}; cout << "The sum of all squares in "; copy(ia1, ia1 + 7, ostream_iterator (cout, " ")); cout << "is: “; int init = 0; cout << inner_product(ia1, ia1 + 7, ia1, init) << endl; cout << "The sum of all cross-products in "; copy(ia1, ia1 + 7, ostream_iterator (cout, " ")); cout << " and "; copy(ia2, ia2 + 7, ostream_iterator (cout, " ")); cout << "is: “; init = 0; cout << inner_product(ia1, ia1 + 7, ia2, init) << endl;

inner_product: definition T inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init, BinaryFunction1 binary_op1, BinaryFunction2 binary_op2); Initializes result to init Initializes result to init For each iterator i in [first1, last1), updates result as follows: For each iterator i in [first1, last1), updates result as follows: result = binary_op1(result, binary_op2(*i, *(first2 + (i - first1))).

Inner Product (string concat) class Cat { class Cat { public: public: Cat(string const &sep): sep(sep) {} Cat(string const &sep): sep(sep) {} string operator()(string const& s1, string const& s2) { string operator()(string const& s1, string const& s2) { return (s1 + sep + s2); } return (s1 + sep + s2); } private: private: string sep; string sep; }; }; string names1[] = {"Frank", "Karel", "Piet"}; string names2[] = {"Brokken", "Kubat", "Plomp"}; cout << "A list of all full names in "; copy(names1, names1 + 3, ostream_iterator (cout, " ")); cout << "and "; copy(names2, names2 + 3, ostream_iterator (cout, " ")); cout << "is:" << inner_product(names1, names1 + 3, names2, string("\t"), Cat("\n\t"), Cat(" ")) << endl;

Parametrized Bubblesort template template class greater { public: bool operator()(const T& a, const T& b) const { return a > b; }; template template class less { public:bool operator()(const T& a, const T& b) const { return a < b; };

Note int x = 3, y = 5; bool b = greater ()(x, y);

Function object version template template void bubblesort(T a[], unsigned size, const C& comp) { for (unsigned i = 0; i < size; ++i) for (unsigned i = 0; i < size; ++i) for (unsigned j = i+1; j < size; ++j) for (unsigned j = i+1; j < size; ++j) if (comp(a[i], a[j])) swap(a[i], a[j]); };

Functional version template template void bubblesort(T a[], unsigned size, bool (*comp)(T&, T&)) { for (unsigned i = 0; i < size; ++i) for (unsigned i = 0; i < size; ++i) for (unsigned j = i+1; j < size; ++j) for (unsigned j = i+1; j < size; ++j) if (comp(a[i], a[j])) swap(a[i], a[j]); };

Bubblesort usage int x[] = {-1, -2, -3, -4, -5}; bubblesort(x, sizeof(x)/sizeof(x[0]), greater ()); bubblesort(x, sizeof(x)/sizeof(x[0]), less ());

Template Enumeration template template class TheVector { private: std::vector vector; public: Enumeration getEnumeration() { return (Enumeration(&vector)); } class Enumeration { … } };

Enumeration (2) class Enumeration { private: private: vector const* vp; vector const* vp; unsigned idx; unsigned idx; public: public: Enumeration(vector const* vector) : Enumeration(vector const* vector) : vp(vector), idx(0) { } vp(vector), idx(0) { } T const& nextElement() { // uses 'T‘ T const& nextElement() { // uses 'T‘ if (idx == vp->size()) if (idx == vp->size()) throw NoSuchElementException(index); throw NoSuchElementException(index); return (*vp)[idx++]; return (*vp)[idx++]; } bool hasMoreElements() { return idx size(); } bool hasMoreElements() { return idx size(); }};

Enumeration (3) TheVector theVector; … TheVector ::Enumeration en = theVector.getEnumeration(); while (en.hasMoreElements()) cout << en.nextElement() << endl;

Issue: template instantiation // file sumVector.h template template T sumVector(T* array, unsigned n) { T sum(0); for (int i = 0; i < n; ++i) sum += array[i]; sum += array[i]; return sum; }

Instantiation (1) #include "sumVector.h" int x[] = {1, 2}; double y[] = {1.1, 2.2}; cout << sumVector(x, 2) << endl << sumVector(y, 2) << endl; If the same template function definition is included in different source files, separately compiled and linked, there will be only one instantiation, per type of template function If the same template function definition is included in different source files, separately compiled and linked, there will be only one instantiation, per type of template function

Instantiation (2) declare a template function, if it is known that the required instantiation is available in another source file: declare a template function, if it is known that the required instantiation is available in another source file: template template T sumVector(T* tp, unsigned n); int v[] = {1, 2}; sumVector(v, 2);

Instantiation (3) declare template functions in header files, keep the definition in a template source file: declare template functions in header files, keep the definition in a template source file: template template T sumVector(T* tp, unsigned n) { return (*tp); return (*tp);} static void* p1 = static_cast (sumVector);

Forcing Instantiations static void* p[] = { static_cast (sumVector), static_cast (sumVector), static_cast (sumVector) static_cast (sumVector)};

Explicit Instantiations template template T sumVector(T *tp, unsigned n) { return (*tp); } template int sumVector (int *, unsigned); template double sumVector (double *, unsigned); template unsigned sumVector (unsigned *, unsigned);