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.

Slides:



Advertisements
Similar presentations
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
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.
CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
14 Templates. OBJECTIVES In this chapter you will learn:  To use function templates to conveniently create a group of related (overloaded) functions.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Templates & STL Instructor: 小黑. Templates  Template serves as a class outline, from which specific classes are generated at compile time.  One template.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
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: 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.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Dr. Yingwu Zhu STL Vector and Iterators. STL (Standard Template Library) 6:14:43 AM 2 A library of class and function templates Components: 1. Containers:
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.
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
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)‏
Defining New Types Lecture 21 Hartmut Kaiser
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.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
C++ Programming Part 2 Michael Griffiths Corporate Information and Computing Services The University of Sheffield
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.
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
A gentle introduction to the standard template library (STL) Some references:
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
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.
CSE 332: C++ data types, input, and output Built-In (a.k.a. Native) Types in C++ int, long, short, char (signed, integer division) –unsigned versions too.
Overview of C++ Polymorphism
Cop3530sp12. Parameter passing call by value- appropriate for small objects that should not be altered by the function call by constant reference- appropriate.
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)
17-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Overview of STL Function Objects
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.
C++ Functions A bit of review (things we’ve covered so far)
Motivation for Generic Programming in C++
Pointers and Dynamic Arrays
C++ Templates.
Motivation and Overview
Pointers and Pointer-Based Strings
Generic Programming Techniques in C++
Templates.
The C++ Algorithm Libraries
ADT Implementations: Templates and Standard Containers
C++ Functions, Classes, and Templates
Pointers & Functions.
CMSC 202 Lesson 22 Templates I.
Abstraction: Generic Programming, pt. 2
Lists - I The List ADT.
Lists - I The List ADT.
Overview of C++ Polymorphism
Pointers and Pointer-Based Strings
Templates I CMSC 202.
Pointers & Functions.
Presentation transcript:

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 a type with another type –Given a type parameter, let you get the other type –Let you control encapsulation of type information Typedefs + specialization (the mechanisms) –Let you give a known type another name –Let you name associated types consistently Across user-defined/built-in const/non-const types Traits (the technique) –Let you associate user-defined and built-in types –Let you provide consistent access across types

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits Basic Example: Associated Types (the Idea) Want to swap the values of two locations in memory Basic idea is simple –Declare a temporary variable –“Remember” value from location i1 aliases in temp –Copy value from location i2 aliases into location i1 aliases –Copy “remembered” value from temp into location i2 aliases But, code to left won’t compile –How can we declare temp ’s type? –How can we get T from I ? // Based on Austern pp. 34 template void swap (I i1, I i2) { T temp = *i1; *i1 = *i2; *i2 = temp; }

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits Typedef + Specialization (the Mechanisms) Use specialization of a general traits struct template –Still have to parameterize struct iterator_traits with typename I –Can’t do full specialization since we’re using type parameter T –Gives us different versions of the iterator_traits struct For user-defined, built-in types For const, non-const types –Remember that the C++ compiler will select the most specific match // Based on Austern, pp. 35 template struct iterator_traits { typedef typename I::value_type value_type; }; template struct iterator_traits { typedef T value_type; }; template struct iterator_traits { typedef T value_type; };

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits Traits (the Technique) Given the iterator type I Traits provide an interface to I ‘s associated types –E.g., iterator_traits ::value_type –Let us obtain and use those types in template code In general, let us go from containers to iterators to traits to associated types –Even within templates template void swap (I i1, I i2) { iterator_traits ::value_type temp = *i1; *i1 = *i2; *i2 = temp; }

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits Another Type Programming Example Goal –Print the contents of different data sets First approach –Use list and vector data stored in ranges –Iterator for ostream lets us print to cout –The copy algorithm Copies data ranges –Get similar code 2 places Desired improvement –Factor out common code –How can we make this code more generic? –What type info do we need to do that? #include // For cout, manipulators. #include // For lists. #include // For vectors. #include // For ostream iterator. using namespace std; int main (int, char *[]) { list l; l.push_back ('a'); l.push_back ('b'); l.push_back ('d'); cout << "list l contains: "; ostream_iterator osic (cout, " "); copy (l.begin(), l.end(), osic); cout << endl; vector v; v.push_back (1); v.push_back (2); v.push_back (4); cout << "vector v contains: "; ostream_iterator osii (cout, " "); copy (v.begin(), v.end(), osii); cout << endl; return 0; }

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits Containers  Iterators  Traits  Types Use of copy algorithm –Takes three iterators Two input iterators One ostream iterator Input iterator types –Can we get those from the container? –If so, how? Output iterator type –Parameterized with char vs. int –Can we get that parameterized type from the input iterators? –If so, how? #include // For cout, manipulators. #include // For lists. #include // For vectors. #include // For ostream iterator. using namespace std; int main (int, char *[]) { list l; l.push_back ('a'); l.push_back ('b'); l.push_back ('d'); cout << "list l contains: "; ostream_iterator osic (cout, " "); copy (l.begin(), l.end(), osic); cout << endl; vector v; v.push_back (1); v.push_back (2); v.push_back (4); cout << "vector v contains: "; ostream_iterator osii (cout, " "); copy (v.begin(), v.end(), osii); cout << endl; return 0; }

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits template struct block{ typedef T value_type; typedef value_type * pointer; typedef value_type & reference; typedef const_value_type* const_pointer; typedef const value_type & const_reference; typedef size_t size_type; …… typedef pointer iterator; typedef const_pointer const_iterator; …… }; From Austern, pp. 61 Containers  Iterators (Types) Every STL container must provide these types

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits template struct block{ …… iterator begin() {return data;} iterator end() {return data+N;} const_iterator begin() const {return data;} const_iterator end() const {return data+N;} …… T data [N]; }; Containers  Iterators (Instances) From Austern, pp. 61 Every STL container must produce iterators of the correct type (Factory Method Pattern)

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits Containers  Iterators  Traits  Types Can now write a (somewhat) generic print_container function template –Takes container type T as a template type parameter –Takes const reference to container t as a function parameter Uses associated types –Obtained from passed container types –Uses typename where necessary Uses iterator accessors –t.begin() and t.end() #include using namespace std; template void print_container (const T & t) { ostream_iterator osi (cout, " "); copy (t.begin(), t.end(), osi); cout << endl; }

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits How Making a Function Generic Can Help Program is now simpler –Manipulates data, containers –Leaves printing details to the generic print_container function template However, there is still one remaining limitation –Cannot use for built-in arrays, or variables like double, or char[] –We will fix this limitation next By changing to a range- based print function interface By declaring our own traits #include "print_container_T.h" #include // For cout. #include // For lists. #include // For vectors. using namespace std; int main (int, char *[]) { list l; l.push_back ('a'); l.push_back ('b'); l.push_back ('d'); cout << "list l contains: "; print_container (l); vector v; v.push_back (1); v.push_back (2); v.push_back (4); cout << "vector v contains: "; print_container (v); return 0; } /* output is list l contains: a b d vector v contains: */

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits Declaring Your Own Traits Could have used pointer traits already provided by the STL –But, it’s good to see the technique itself again So you can associate other types as needed –Notice use of partial specialization and use of typename, again –Notice separate partial specializations for const and non-const, again Now we have our associated types –Can use in an even more generic print function template template struct print_traits { typedef typename T::value_type value_type; }; // partial specialization for pointers template struct print_traits { typedef T value_type; }; // partial specialization for const pointers template struct print_traits { typedef T value_type; };

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits Using Your Traits in a Generic Function Template Generic print function template –Takes iterator type parameter –Takes iterators as function parameters (define a range) Used typedef for convenience –Here, as a kind of local type name declaration –Avoid excessive use, but can aid coding style in some cases Applies generically to iterators –Including const and non-const pointers to memory locations #include "print_T.h" #include using namespace std; template void print (I i, I j) { typedef typename print_traits ::value_type VTYPE; ostream_iterator osi (cout, " "); copy (i, j, osi); cout << endl; }

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits How Generic Type Programming Has Helped Program is as simple as it was before But now has added capabilities –Can print variables –Can print arrays All using generic type programming in C++ #include "print_T.h" #include // For cout, manipulators. #include // For lists. #include // For vectors. #include // For strlen. using namespace std; int main (int, char *[]) { list l; l.push_back ('a'); l.push_back ('b'); l.push_back ('d'); cout << "list l contains: "; print (l.begin(), l.end()); vector v; v.push_back (1); v.push_back (2); v.push_back (4); cout << "vector v contains: "; print (v.begin(), v.end ()); char * s = "hello, world!"; cout << "C-style string s contains: " << endl; print (s, s + strlen(s)); const double d = 3.141; cout << "Const double precision floating \n" " point number d contains: "; print (&d, (&d)+1); return 0; } /* output is list l contains: a b d vector v contains: C-style string s contains: h e l l o, w o r l d ! Const double precision floating point number d contains: */

CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits Concluding Remarks Associated types are a powerful idea in C++ –Let you use templates more effectively, easily –Let you make programs simpler, better encapsulated Typedefs give a way to provide consistent type names –Let user-defined types declare associated types –Let you create type names for other purposes, convenience Traits abstract away problems with associating types –Across user-defined, built-in, const, non-const types –Ensures consistency, makes types/algorithms more generic The STL takes these ideas even further –Allows algorithms to be bound to specific iterator categories –For arbitrary reasons, like performance/correctness trade-off