1 of 24 Concepts: Linguistic Support for Generic Programming in C++ Douglas GregorJaakko JärviJeremy Siek Inidiana UniversityTexas A&M UniversityRice University.

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

Chapter 18 Vectors and Arrays
Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
TEMPLATES Lecture Presented By SHERY KHAN Object Orienting Programming.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
ConceptClang: An Implementation of C++ Concepts in Clang Larisse Voufo, Marcin Zalewski, and Andrew Lumsdaine Open Systems Lab, Indiana University.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
 2006 Pearson Education, Inc. All rights reserved Templates.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
 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.
Type Inference: CIS Seminar, 11/3/2009 Type inference: Inside the Type Checker. A presentation by: Daniel Tuck.
Abstract Data Types and Encapsulation Concepts
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Operator Overloading 1. Introduction Let’s define a class for Complex numbers: class Complex { private: double real, image; public: Complex () : real(0.0),
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: 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.
1 Concepts: Linguistic Support for Generic Programming in C++ Douglas Gregor Jeremy Siek Gabriel Dos Reis Jaakko Järvi Bjarne Stroustrup Andrew Lumsdaine.
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
Programming Languages and Paradigms Object-Oriented Programming (Part II)
C++ Concepts : Introduction, Goals, and Applications Mohammad Soryani Mazandaran University of Science and Technology
Programming Language C++ Xulong Peng CSC415 Programming Languages.
Generic Programming Johan Torp. Agenda GP introduction GP in perspective Questions * GP = Generic programming in C++
Programming Language Support for Generic Libraries Jeremy Siek and Walid Taha Abstract The generic programming methodology is revolutionizing the way we.
GPCE'04, Vancouver 1 Towards a General Template Introspection Library in C++ István Zólyomi, Zoltán Porkoláb Department of Programming Languages and Compilers.
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.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
1 A Comparative Study Of Language Support for Generic Programming Oopsla 2003 Roland Garcia Jaakko Jarvi Andrew Lumsdaine Jeremy Siek Jeremiah Wilcock.
1 An Introduction to Concepts in C++0x Douglas Gregor Indiana University (I’m Gary... and these are Doug’s slides)
Generic Programming in C++. Generic Parameters Function for squaring a number: Function for squaring a number: sqrt(x) { return x * x; } C version: C.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
CS212: Object Oriented Analysis and Design Lecture 24: Introduction to STL.
Overview of C++ Templates
Reusing Code in C++ Has-a relationship Classes with member objects(containment) The valarray template class Private & protected inheritance Multiple inheritance.
Concepts in C++. Templates in current C++ C++ template is typeless No language support for constrained generics Accidental errors found in instantiation.
1 Future of Abstraction Alexander Stepanov. 2 Outline of the Talk Outline of the Talk  What is abstraction?  Abstraction in programming  OO vs. Templates.
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.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 10 Abstraction - The concept of abstraction is fundamental in programming - Nearly all programming.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
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 –
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
 2006 Pearson Education, Inc. All rights reserved Templates.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Generic Programming in C++ Giuseppe Attardi Università di Pisa.
Motivation for Generic Programming in C++
Programming with ANSI C ++
How to be generic Lecture 10
C++ Templates.
Templates.
Review: Two Programming Paradigms
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.
Constructors and Other Tools
Abstraction: Generic Programming, pt. 2
Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
A Deeper Look at Classes
Presentation transcript:

1 of 24 Concepts: Linguistic Support for Generic Programming in C++ Douglas GregorJaakko JärviJeremy Siek Inidiana UniversityTexas A&M UniversityRice University Bjarne Stroustrup Gabriel Dos RiezAndrew Lumsdaine Texas A&M University Texas A&M University Inidiana University OOPSLA- 2006

2 of C++ Templates Today “ Dynamic Typing ” :  Templates are prepared to do anything !  If it fails – it fails ! Consequences:  Very powerful tool  Very difficult to use Templates are smart macros !!! Bjarne Sroustrup

3 of Horrors of STL documentation Requirements table for Copy Constructible return typeexpression T(t) T(u) T::~T() T*&t Const T*&u Type T is a model of Copy Constructible, t is a value of type T and u is a value of type const T.

4 of Motivation Consider : Attempt to compile - produces 2 Kb of error messages! Provided errors point to the implementation of STL sort()! The only clue that this error was triggered by users code: Actual error: STL sort() requires Random Access Iterartos.OutputOutput list lst; sort(lst.begin(),lst.end()); sort_list.cpp:8: instantiated from here

5 of Concepts to the Rescue Concept: a set of requirements (syntactic, semantic, performance-related) on a template parameter.  Discussed extensively in the literature Modeling: A type that implements the requirements of a concept is said to model the concept Concept Refinement: A refines B if every type that models A also models B. C++ Concepts: language extension due to B.S and friends…  Objectives  Precise specification of requirements  Better than obscure documentation  Streamline writing and using templates  Backwards compatibility.  Preserve template flexibility and efficiency.

6 of Language Support for Concepts Demonstrating major concept features : /* Concept Defenition */ concept LessThanComparable { bool operator<(T x,T y); } /* use constraint */ template where LessThanComparable const T& min(const T& x, const T& y){ return x<y ? x:y; }

7 of Same-type constraints The only built-in concept. Requires that 2 type expressions produce same type. Built-in to enable the type checking of constrained templates. template<MutableForwardIterator iter1, MutableForwardIterator iter2> where SameType<iter1::value_type, iter2::value_type> void iter_swap(Iter1 a,Iter2 b){ swap(*a,*b); }

8 of Negative constraints Why? Disambiguation! template void sort(S&) {} template where LessThanComparable void sort(S& s){ quick_sort(s); } … SortedArray arr; sort(arr) /* ERROR! Ambiguity ! */ template void sort(S&) {} template where LessThanComparable && !SortedSequence void sort(S& s){ quick_sort(s); } … SortedArray arr; sort(arr); /* OK ! No ambiguity ! */

9 of Constraint Propagation Large template libraries: templates freely call each other. If template T1, calls T2, then T1 must make all demands that T2 places on X. Without propagation sort_container() would fail to compile, because it doesn’t guarantee the T is CopyConstructible. template class list{... }; template void sort_containter(list & c){ c.sort(); }

10 of Concept Definition Namespace-level entity concept InputIterator : CopyConstructable /* refinement clause */{ /* Associated types */ typename value_type = Iter::value_type; typename pointer = Iter::pointer; /* Nested where clause */ where Arrowable... /* Signature */ Iter& operator++(Iter&); }

11 of Refinement “Is-a” relationship between concepts. Concepts = sets of requirements, Refinement = set inclusion  "Multiple Inheritance” ? OK!  "Repeated Inheritance"? OK! A concept may refine any number of other concepts concept BidirectionalIterator : ForwardIterator {... };

12 of Associated Types Often types rely on related types  E.g., graph type relies on edge and vertex. This concept requires from model type to name its edge and vertex types. A concept may provide a default for an associated type. concept Graph { typename edge; typename vertex;... edge find_edge(vertex u,vertex v,const G& g); };

13 of Nested Requirements Allow the use of other concepts to constrain the parameters and associated types. Used to express the requirement that container’s value_type must be the same type as the iterators’s value_type. concept Container { typename value_type; InputIterator iterator; where SameType<value_type, InputIterator ::value_type>; }

14 of Function Signatures An operator signature can be satisfied by free function or a member function definition. concept EqualityComparable { bool operator==(const T& x,const T& y); bool operator!=(const T& x,const T& y) { return !(x==y);} } concept Container { bool X::empty() const; X::X(int n); };

15 of Overloading and Specialization Template function names overloaded on their where clause. template /* 1 */ void advance(Iter& iter,Iter::difference_type n){ while (n--) ++iter;} } template /* 2 */ void advance(Iter& iter,Iter::difference_type n){ if (n>0) {while (n--) ++iter;} else {while (n++) ++iter; } } template /* 3 */ void advance(Iter& iter,Iter::difference_type n){ iter += n; } void advancement(istream_iterator ii, list ::interator lsti,vector ::iterator vi){ advance(ii,17); /* advance 1 invoked */ advance(lsti,17); /* advance 2 invoked */ advance(vi,17);} /* advance 3 invoked */

16 of Concept Maps Concept_map defines a mapping that states how the type models the concept. We don’t need to redesign student_record type! class student_record{ public: string id; string name; bool id_equal(const student_record& ); bool name_equal(const student_record& ); } concept_map EqualityComparbale { bool operator==(const student_record& x, const student_record& y) { return a.id_equal(b); } }

17 of Concept Maps (cont.) Concept map templates used to compose generic libraries template concept_map Matrix { typedef int value_type; int rows(const G& g){return num_vertices(g);} int cols(const G& g){return num_vertices(g);} double operator()(const G& g,int i,int j){ edge e=find_edge(ith_vertex(i,g),g); if(e) return 1; else return 0; } My_graph g = read_graph(); vector x = compute_ith_eigenvector(g,0);

18 of Implicit and Explicit Concepts To make bool fit it : concept EqualityComparable { bool operator==(const T& x,const T& y); bool operator!=(const T& x,const T& y); {return !(x==y);} } concept_map EqualityComparable { bool operator==(const bool& x, const bool& y){ return (x==y); } To make char fit it : concept_map EqualityComparable { bool operator==(const char& x, const char& y){ return (x==y); } To make it fit automatically : auto concept EqualityComparable { bool operator==(const T& x,const T& y); bool operator!=(const T& x,const T& y); {return !(x==y);} }

19 of ConceptGCC = GCC + Concepts Inclusion Model: template definition must be available where template is used.  No separate compilation ConceptGCC: retain inclusion model compilation for backward compatibility and efficiency preservation. Precludes separate compilation for C++ templates. The interaction between specialization and separate compilation is being explored.

20 of Implementation Technique Concepts: "compiled" to ordinary templates. Concept maps: "compiled" to specialized templates. concept Addable { T operator+(const T&,const T&); }; concept_map Addable { big_int operator+(const big_int& a, const big_int& b) {return a.plus(b);} }; template class Addable; template<> class Addable { static big_int operator+(const big_int& a, const big_int& b) {return a.plus(b);} };

21 of Implementation Technique Constrained template: “compiled” to explicit calls. template where Addable && Assignable value_type sum(Iter first,Iter last, Iter::value_type s){ for(;first!=last;++first) s=s+*first; return s; } s = s + *first Addable ::operator+(s, InputIterator ::operator*(first))

22 of Type-checking Templates ConceptGCC generates archetype – placeholder type. Archetypes define only operations stated by the concept requirements. Dependent expressions transformed into non- dependent in the first stage. Entire template definition is type-checked in parse-time. This way a modular type-checking is enabled.

23 of Final STL example return typeexpression T(t) T(u) T::~T() T*&t Const T*&u Type T is a model of Copy Constructible, t is a value of type T and u is a value of type const T. STL documentation Concept translation auto concept CopyConstructible { T::T(const T&); T::~T(); T* operator&(T&); const T* operator&(const T&); };

24 of STL Evaluation Results Uncovered STL errors and ambiguities. Concept-enhanced STL is better from user’s and implementer’s point of view. Provided (nearly) modular type-checking. Shorter and clearer error messages. Provided near-perfect backward compatibility. ConceptGCC available at

1 of 24 Back…