CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.

Slides:



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

CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
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++ 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.
CSE 332: Combining STL features Combining STL Features STL has containers, iterators, algorithms, and functors –With several to many different varieties.
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.
CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
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.
Generic Programming Johan Torp. Agenda GP introduction GP in perspective Questions * GP = Generic programming in C++
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)‏
Policy Adaptors and the Boost Iterator Adaptor Library David Abrahams, Jeremy Siek, Indiana University.
Programming using C# for Teachers Introduction to Objects Reference Types Functions of Classes Attributes and Types to a class LECTURE 2.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
Lecture 19 CIS 208 Wednesday, April 06, Welcome to C++ Basic program style and I/O Class Creation Templates.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
ITERATORS. Iterator An iterator in C++ is a concept that refines the iterator design pattern into a specific set of behaviors that work well with the.
Overview of C++ Templates
Concepts in C++. Templates in current C++ C++ template is typeless No language support for constrained generics Accidental errors found in instantiation.
CSE 332: Design Patterns Introduction to Design Patterns You’ve seen design patterns several times this semester –The Iterator pattern has been discussed.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
PROGRAMMING TECHNIQUES Based on “Modern C++ Design” BY ALEXANDRESCU BOGDAN PENKOVSKY 2010.
Overview of C++ Polymorphism
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
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)
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (this Friday). Today: –Templates. –STL –Smart Pointers.
Overview of STL Function Objects
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
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.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
MAITRAYEE MUKERJI Object Oriented Programming in C++
1 C++ Classes and Data Structures Course link…..
Chapter 15 - C++ As A "Better C"
Motivation for Generic Programming in C++
C++ Lesson 1.
Introduction to C++ (Extensions to C)
C++ Templates.
Lecture 7-2 : STL Iterators
Introduction to C++ Systems Programming.
Generic Programming Techniques in C++
The C++ Algorithm Libraries
Reserved Words.
Object-Oriented Programming (OOP) Lecture No. 32
Lecture 7-2 : STL Iterators
C++ Functions, Classes, and Templates
Chapter 5 Function Basics
Object-Oriented Programming (OOP) Lecture No. 39
Pointers & Functions.
CMSC 202 Lesson 22 Templates I.
Overview of C++ Polymorphism
Templates I CMSC 202.
Pointers and dynamic objects
Pointers & Functions.
CS 144 Advanced C++ Programming February 21 Class Meeting
Presentation transcript:

CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements –Otherwise, the code won’t compile (and errors will say why) The set of requirements imposed is called a concept 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; } const T & Iterator

CSE 332: C++ templates and generic programming II Concept Refinement Motivates Overriding 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 How can we override function, class, and struct templates for specific parameterized types? C1 C2 T1T2 T3T4 C0 containment transitivity can substitute, e.g., T3 for T1

CSE 332: C++ templates and generic programming II Template Specialization: Overriding on Types Two examples –Fully specialize a function template to print different types –Partially specialize a struct template for iterator traits First example will refine output code several times –Ending up with a specialized reusable function template –Shows how to write fully specialized function templates –Can only fully (not partially) specialize a function template Second example shows the iterator traits idiom –Used by the STL to make pointers random access iterators –Wraps a typedef for an associated type in a struct –Allows partial specialization for specific pointer types

CSE 332: C++ templates and generic programming II First Example: Printing Different Types #include using namespace std; int main (int, char *[]) { int i = 7; bool b = false; int * ip = &i; char * cp = "hello, world!"; void * vp = cp; cout << "i is " << i << endl; cout << "b is " << b << endl; cout << "ip is " << ip << endl; cout << "cp is " << cp << endl; cout << "vp is " << vp << endl; return 0; } Large number of types in C++ Each handled a bit differently For example, << with ostream Simply giving to cout gives i is 7 b is 0 ip is 0xfef69094 cp is hello, world! vp is 0x8048a3c We can improve on this!

CSE 332: C++ templates and generic programming II Improve the Output for bool #include using namespace std; int main (int, char *[]) {... cout << "i is " << i << endl; cout << "b is " << boolalpha << b << endl; cout << "ip is " << ip << endl; cout << "cp is " << cp << endl; cout << "vp is " << vp << endl; return 0; } First, fix how bool is output Use an iostream manipulator std::boolalpha –prints true or false –Instead of 1 or 0 Now we get i is 7 b is false ip is 0xfef2aa04 cp is hello, world! vp is 0x8048b0c But what about the pointers?

CSE 332: C++ templates and generic programming II Improve the Output for Pointers #include using namespace std; int main (int, char *[]) {... cout << "i is " << i << endl; cout << "b is " << boolalpha << b << endl; cout << "ip is " << ip << " (points to " << *ip << ")" << endl; cout (cp) << " (points to \"" << cp << "\")" << endl; cout << "vp is " << vp << endl; return 0; } Now, fix pointers Use reinterpret_cast –Convert char * to void * Use dereferencing –Convert int * to int Now we have what we want i is 7 b is false ip is 0xfef23584 (points to 7) cp is 0x8048b70 (points to "hello, world!") vp is 0x8048b70 But, we don’t want to have to do all that over again the next time we want to print

CSE 332: C++ templates and generic programming II Refactor the Code with a Function Template #include using namespace std; #include "common_T.h" int main (int, char *[]) { int i = 7; bool b = false; int * ip = &i; char * cp = "hello, world!"; void * vp = cp; print(cout, "i is ", i); print(cout, "b is ", b); print(cout, "ip is ", ip); print(cout, "cp is ", cp); print(cout, "vp is ", vp); return 0; } Define print function template –Consistent interface across types –Just pass message, variable With this template we get i is 7 b is 0 ip is 0xfeea28f4 cp is hello, world! vp is 0x8048adc Right back where we started? template void print (ostream & os, const char * message, const T & t) { os << message << t << endl; }

CSE 332: C++ templates and generic programming II Fully Specialize to Override Function Templates typedef char * charptr; typedef int * intptr; template <> void print (ostream & os, const char * message, const bool & b) { os << message << std::boolalpha << b << endl; } template <> void print (ostream & os, const char * message, const charptr & s) { os << message (s); if (s != 0) { os << " (points to \"" << s << "\")"; } os << endl; } template <> void print (ostream & os, const char * message, const intptr & ip) { os << message << ip; if (ip != 0) { os << " (points to " << *ip << ")"; } os << endl; } Specialize on individual types bool char * int * –Notice the use of typedef With specialization, we get i is 7 b is false ip is 0xfeebf064 (points to 7) cp is 0x8048c30 (points to "hello, world!") vp is 0x8048c30 And, we can reuse the solution! template void print (ostream & os, const char * message, const T & t) { os << message << t << endl; }

CSE 332: C++ templates and generic programming II Second Example: Iterator Traits Start with a few concrete types for category tags –E.g., empty structs for input, output, fwd, bidir, and rand categories Those tags are used as associated types for iterators –Iterator category –Made available by partial specialization override for pointers struct input {}; // empty structs for type tags struct output {}; struct fwd : public input {}; // note inheritance struct bidir : public fwd {}; struct rand : public bidir {}; template struct iterator_traits {... typedef typename I::iterator_category iterator_category; }; template struct iterator_traits {... typedef rand iterator_category; }; template struct iterator_traits {... typedef rand iterator_category; }; (actually, random_access_iterator_tag )

CSE 332: C++ templates and generic programming II Algorithm Dispatching via Category Tags Static dispatching –Implementations provide different signatures –Iterator type is evaluated at compile-time –Links to the best implementation Notice how type tags are used // Based on Austern, pp. 38, 39 template void move (Iter i, Distance d, fwd) { while (d>0) {--d; ++i;} // O(d) } template void move (Iter i, Distance d, rand) { i += d; // O(1) } template void move (Iter i, Distance d) { move (i, d, iterator_traits :: iterator_category() ) } concrete tag (empty struct) type explicit constructor call concrete tag (empty struct) type

CSE 332: C++ templates and generic programming II Summary of Templates and Specialization 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 Fully specialize function templates (and fully or partially specialize class and struct templates) to override template behaviors, etc. for specific types