Concepts in C++. Templates in current C++ C++ template is typeless No language support for constrained generics Accidental errors found in instantiation.

Slides:



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

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.
Chapter 17 Templates. Generic Algorithms Algorithms in which the actions or steps are defined, but the data types of the items being manipulated are not.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
1 STL and Its Design Principles Alexander Stepanov.
ConceptClang: An Implementation of C++ Concepts in Clang Larisse Voufo, Marcin Zalewski, and Andrew Lumsdaine Open Systems Lab, Indiana University.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
Generic programming Define software components with type parameters –A sorting algorithm has the same structure, regardless of the types being sorted –Stack.
Generic programming Define software components with type parameters –A sorting algorithm has the same structure, regardless of the types being sorted –Stack.
 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; }
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.
Templates and the STL.
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
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:
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
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
Generic Programming Johan Torp. Agenda GP introduction GP in perspective Questions * GP = Generic programming in C++
Templates. Before we dive in 2 Preprocessing Compilation Linkage.
C++ Template Metaprogramming Why, When and How? Zoltán Porkoláb Dept. of Programming Languages and Compilers, Faculty of Informatics Eötvös.
Programming Language Support for Generic Libraries Jeremy Siek and Walid Taha Abstract The generic programming methodology is revolutionizing the way we.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
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.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
CSE 332: C++ STL functors STL Functors: Functions vs. Function Objects STL Functors support function call syntax Algorithms invoke functions and operators.
 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
Intro to the C++ STL Timmie Smith September 6, 2001.
Csi2172 class 5 Midterm: June 12. constructor Special method used to create objects of the class Never has a return type. Is called automatically upon.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 RAD due Friday in your Wiki. Presentations week 6 – next week. Schedule on next slide. Today: –Operator.
1 Future of Abstraction Alexander Stepanov. 2 Outline of the Talk Outline of the Talk  What is abstraction?  Abstraction in programming  OO vs. Templates.
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.
Copyright © 2009 – Curt Hill Standard Template Library An Introduction.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
Templates Where the TYPE is generic. Templates for functions Used when the you want to perform the same operation on different data types. The definition.
Lecture 7.  There are 2 types of libraries used by standard C++ The C standard library (math.h) and C++ The C++ standard template library  Allows us.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
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
1 of 24 Concepts: Linguistic Support for Generic Programming in C++ Douglas GregorJaakko JärviJeremy Siek Inidiana UniversityTexas A&M UniversityRice University.
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
Object-Oriented Programming (OOP) Lecture No. 42.
Templates 3 Templates and type parameters The basic idea templates is simple: we can make code depend on parameters, so that it can be used in different.
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.
Washington WASHINGTON UNIVERSITY IN ST LOUIS More on the STL: Function Objects and Generic Algorithms in the STL Fred Kuhns Computer Science and Engineering.
Motivation for Generic Programming in C++
How to be generic Lecture 10
Templates.
Templates.
18 – Sequential Containers
Elements are always copied when they are put into a container
Abstraction: Generic Programming, pt. 2
CISC/CMPE320 - Prof. McLeod
Templates and Iterators
Linked Lists Templates and Iterators
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:

Concepts in C++

Templates in current C++ C++ template is typeless No language support for constrained generics Accidental errors found in instantiation => complex, long, hard to understand error messages

Example... std::list intList; intList.push_back(42);... intList.push_back(5);... std::sort(intList.begin(), intList.end()); Compiled with gcc:

Error messages /usr/include/c++/4.1.3/bits/stl_algo.h: In function ‘void std::sort(_RandomAccessIterator, _RandomAccessIterator) [with _RandomAccessIterator = std::_List_iterator ]’: templ.cpp:13: instantiated from here /usr/include/c++/4.1.3/bits/stl_algo.h:2713: error: no match for ‘operator-’ in ‘__last - __first’ /usr/include/c++/4.1.3/bits/stl_algo.h: In function ‘void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator) [with _RandomAccessIterator = std::_List_iterator ]’: /usr/include/c++/4.1.3/bits/stl_algo.h:2714: instantiated from ‘void std::sort(_RandomAccessIterator, _RandomAccessIterator) [with _RandomAccessIterator = std::_List_iterator ]’ templ.cpp:13: instantiated from here

Cont. /usr/include/c++/4.1.3/bits/stl_algo.h:2360: error: no match for ‘operator+’ in ‘__first + 16’ /usr/include/c++/4.1.3/bits/stl_algo.h: In function ‘void std::__insertion_sort(_RandomAccessIterator, _RandomAccessIterator) [with _RandomAccessIterator = std::_List_iterator ]’: /usr/include/c++/4.1.3/bits/stl_algo.h:2363: instantiated from ‘void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator) [with _RandomAccessIterator = std::_List_iterator ]’ /usr/include/c++/4.1.3/bits/stl_algo.h:2714: instantiated from ‘void std::sort(_RandomAccessIterator, _RandomAccessIterator) [with _RandomAccessIterator = std::_List_iterator ]’ templ.cpp:13: instantiated from here /usr/include/c++/4.1.3/bits/stl_algo.h:2273: error: no match for ‘operator+’ in ‘__first + 1’

Cont 2. /usr/include/c++/4.1.3/bits/stl_algo.h:2363: instantiated from ‘void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator) [with _RandomAccessIterator = std::_List_iterator ]’ /usr/include/c++/4.1.3/bits/stl_algo.h:2714: instantiated from ‘void std::sort(_RandomAccessIterator, _RandomAccessIterator) [with _RandomAccessIterator = std::_List_iterator ]’ templ.cpp:13: instantiated from here /usr/include/c++/4.1.3/bits/stl_algo.h:2279: error: no match for ‘operator+’ in ‘__i + 1’

And the reason is: …in the STL implementation? The fact: sort requires random access iterator but list has only forward iterator But only this line refers to that: templ.cpp:13: instantiated from here /usr/include/c++/4.1.3/bits/stl_algo.h:2273: error: no match for ‘operator+’ in ‘__first + 1’

C++0x Well-known problem in industrial application In other languages (java, Eiffel, ADA) there are constrained generics In C++0x, there will be concepts

The language components Concept:  Names requirements against template arguments Concept_map:  Semantic relationship between a type and a concept Requires  The concrete requirement list agains template arguments of a class or function

Concept List of function signatures and associated types Like: LessThanComparable concept concept LessThanComparable { bool operator<(T a, T b); };

Requires LessThanComparable concept in a concrete template algorithm: template requires LessThanComparable T min(const T& a, const T& b)‏ { return a < b ? a : b; };

Requires in other way: If a concept defines constraints on only one template parameter, there is a simpler way: template T min(const T& a, const T& b)‏ { return a < b ? a : b; }; „Type”of a template

A bit more complex example concept Regular { // default constructor T:: T(); // copy constructor T:: T(const T&); // destructor T::˜T(); // copy assignment T& operator=(T&, const T&); // equality comparison bool operator==(const T&, const T&); // inequality comparison bool operator!=(const T&, const T&); // swap void swap(T&, T&); };

Multi-Type Concept Concepts may define requirements on more than one types: concept Convertible { operator U(const T&); }; And there is a way to express default parameters concept EqualtyComparable { bool operator==(T, U)‏ };

Example of Multi-Type Concepts concept InputIterator { Iter :: Iter (); // default constructor Iter :: Iter (const Iter &); // copy constructor Iter ::˜ Iter (); // destructor Iter & operator=(Iter&, const Iter&); // copy assignment Value operator ∗ (const Iter&); // dereference Iter & operator++(Iter&); // pre- increment Iter operator++(Iter&, int); // post- increment bool operator==(const Iter&, const Iter&); // equality comparison bool operator!=(const Iter&, const Iter &); // inequality comparison void swap(Iter &, Iter &); // swap };

Concepts: composition „Regular” concept used for InputIterator concept: concept InputIterator { requires Regular ; Value operator ∗ (const Iter&); // dereference Iter& operator++(Iter&); // pre-increment Iter operator++(Iter&, int); // post-increment };

Concepts: refinement concept InputIterator : Regular { Value operator ∗ (const Iter&); // dereference Iter& operator++(Iter&); // pre-increment Iter operator++(Iter&, int); // post-increment }; Hint: if hierarchy, then refinement, Difference: in concept_map definition

A template using InputIterator concept template requires InputIterator void print(Iter first, Iter last)‏ { while (first != last)‏ { std::cout << *first++; } std::cout << std::endl; }

The real InputIterator concept concept InputIterator <typename Iter, typename Value, typename Reference typename Pointer, typename Di ff erence> { requires Regular ; requires Convertible ; Reference operator ∗ (const Iter&); // dereference Iter& operator++(Iter&); // pre-increment Iter operator++(Iter&, int); // post-increment //... }

The real template function using InputIterator template<typename Iter, Regular V, typename R, typename P, typename D> requires InputIterator void print(Iter first, Iter last)‏ { while (first != last)‏ { std::cout << *first++; } std::cout << std::endl; }

Associated Types Associated types: concept InputIterator { typename value type; typename reference; typename pointer; typename di ff erence type; requires Regular ; requires Convertible ; reference operator ∗ (const Iter&); Iter& operator++(Iter&); Iter operator++(Iter&, int); //... };

Template using InputIterator Now we have only one template parameter: template requires Regular void print(Iter first, Iter last) { while (first != last) { std::cout << *first++; } std::cout << std::endl; }

Concept_map Semantic relationship between a type and a concept: Example: looking for the best student: struct Student { std:string name; double avg; };... std::list l;... std::cout << (*std::min_element(l.begin(), l.end())).name << std::endl;

Concept_map 2 But operator< is not defined on Student Non-intrusive solution using concept_map: concept_map LessThanComparable { bool operator<(Diak a, Diak b) { return a.atlag < b.atlag; } };

Concept_map 3 If operator< is defined on some type X, we don’t need to redefine: concept_map LessThanComparable {} auto keyword: no concept_map is required

Other examples for Concept_map Suppose InputIterator is auto Then this partial concept_map definition is valid concept map InputIterator { typedef char value type ; typedef char& reference ; typedef char ∗ pointer ; typedef std::ptrdi ff _t di ff erence type ; }; The rest is generated automaticaly

More Concept_map If implicite (auto) declaration is not valid, e.c.: we want to define to use int-s, az iterator: concept map InputIterator { typedef int value type; typedef int reference; typedef int ∗ pointer; typedef int difference type; int operator ∗ (int x) { return x; } }; Thus, we could inialitize containers. std::copy(1, 101, v.begin());

Concept_map template concepts and concept_maps can be tempatized All the pointers are iterators template concept_map InputIterator { typedef T value type ; typedef T& reference ; typedef T ∗ pointer ; typedef std:: ptrdi ff t di ff erence type ; };

A container adaptor With concept, concept_map container adaptors could be defined without wrapper classes. concept Stack { typename value type; void push(X&, const value type&); void pop(X&); value type top(const X&); bool empty(const X&); };

And it’s concept_map template concept_map Stack > { typedef T value type; void push(std::vector & v, const T& x){ v.push_back(x); } void pop(std:: vector & v){ v.pop_back(); } T top(const std::vector & v){ return v.back(); } bool empty(const std::vector & v){ return v.empty(); } };

Concept-based Overloading Best matching template will be instantiated, Better way to implement many STl functions.

The advance fv. declarations template void advance(Iter& x, Iter::difference_type n) { while (n > 0) { ++x; --n; } } template void advance(Iter& x, Iter::difference_type n) { if (n > 0) while (n > 0) { ++x; --n; } else while (n < 0) { --x; ++n; } } template void advance(Iter& x, Iter::difference_type n) { x += n; }

Negative constraint template class dictionary { // slow, linked-list implementation }; template requires !Hashable class dictionary { // balanced binary tree implementation }; template class dictionary { // hash table implementation };

The error messages For the first example:... std::list intList; intList.push_back(42);... intList.push_back(5);... std::sort(intList.begin(), intList.end()); We got this compiler error: l istconc.cpp: In function ‘int main()’: listconc.cpp:9: error: no matching function for call to ‘sort(std::_List_iterator, std::_List_iterator )’ /home/lupin/local/conceptgcc/bin/../lib/gcc/i686-pc-linux- gnu/4.3.0/../../../../include/c++/4.3.0/bits/stl_algo.h:2874: note: candidates are: void std::sort(_Iter, _Iter) [with _Iter = std::_List_iterator ] listconc.cpp:9: note: no concept map for requirement ‘std::MutableRandomAccessIterator >’