SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
Generic programming 
Anton.Kolotaev@gmail.com
Please visit: 
www.generic-programming.org 
www.boost.org
Generic Programming 
• Programming paradigm for developing efficient, 
reusable software libraries 
• Three primary tasks: 
• Categorize abstractions in a domain into 
concepts 
• Implement generic algorithms based on 
concepts 
• Build concrete models for the concepts
Characteristics of Generic Libraries 
• Reusable: able to operate on user-defined types 
• Composable: able to operate on data types 
defined in another library 
• Efficient: performance on par with non-generic, 
hand-coded implementations
Generic Programming Process 
1. The Generic Programming process focuses on finding 
commonality among similar implementations of the same algorithm, 
then providing suitable abstractions in the form of concepts so that 
a single, generic algorithm can realize many concrete 
implementations. 
2. This process, called lifting, is repeated until the generic algorithm 
has reached a suitable level of abstraction, where it provides 
maximal reusability without sacrificing performance. 
3. Dual to the lifting process is specialization, which synthesizes 
efficient concrete implementations for particular uses of a generic 
algorithm. Only by balancing the lifting and specialization processes 
can we ensure that the resulting generic algorithms are both 
reusable and efficient.
Lifting Basic Types 
int sum(int* array, int n) { 
int result = 0; 
for (int i = 0; i < n; ++i) 
result = result + array[i]; 
return result; 
} 
float sum(float* array, int n) { 
float result = 0; 
for (int i = 0; i < n; ++i) 
result = result + array[i]; 
return result; 
} 
template<typename T> 
T sum(T* array, int n) { 
T result = 0; 
for (int i = 0; i < n; ++i) 
result = result + array[i]; 
return result; 
}
Lifting Basic Types 
std::string concatenate(std::string* array, 
int n) { 
std::string result = ""; 
for (int i = 0; i < n; ++i) 
result = result + array[i]; 
return result; 
} 
// Requirements: 
// T must have a default constructor that produces the identity value 
// T must have an additive operator + 
// T must have an assignment operator 
// T must have a copy constructor 
template<typename T> 
T sum(T* array, int n) { 
T result = T(); 
for (int i = 0; i < n; ++i) 
result = result + array[i]; 
return result;}
Lifting Containers 
// Requirements: 
// T must have a default constructor that produces the identity 
// value 
// T must have an additive operator + 
// T must have an assignment operator 
// T must have a copy constructor 
// Container must have an indexing operator [] that returns a T 
template<typename Container, typename T> 
T sum(const Container& array, int n) { 
T result = T(); 
for (int i = 0; i < n; ++i) 
result = result + array[i]; 
return result; 
}
Lifting Iteration 
template<typename T> 
struct list_node { 
list_node<T>* next; 
T value; 
}; 
struct linked_list { 
list_node<T>* start; 
}; 
template<typename T> 
T sum(list_node<T> list, int n) { 
T result = 0; 
for (list_node<T>* current = list.start; 
current != NULL; current = current->next) 
result = result + current->value; 
return result; 
}
Lifting Iteration 
// Requirements: 
// T must have an additive operator + 
// T must have an assignment operator 
// T must have a copy constructor 
// I must have an inequality operator != 
// I must have a copy constructor 
// I must have an operation next() that moves to the next value in 
// the sequence 
// I must have an operation get() that returns the current value (of 
// type T). 
template<typename I, typename T> 
T sum(I start, I end, T init) { 
for (I current = start; current != end; current = next(current)) 
init = init + get(current); 
return init; 
}
Concepts 
// Requirements: 
// T must have an equality operator == 
// T must have a copy constructor 
// I must have an inequality operator != 
// I must have a copy constructor 
// I must have an assignment operator 
// I must have an operation next() that moves to the next value in 
// the sequence 
// I must have an operation get() that returns the current value 
// (of type T). 
template<typename I, typename T> 
I find(I start, I end, T value) { 
for (I current = start; current != end; current = next(current)) 
if (get(current) == value) 
return current; 
return end; 
}
Concepts 
Concept Requirements 
CopyConstructible<T> T must have a copy constructor 
Assignable<T> T must have an assignment operator 
Addable<T> T must have an operator+ that takes two T values and returns a T 
EqualityComparable<T> T must have an operator== comparing two Ts and returning a bool. 
T must have an operator!= comparing two Ts and returning a bool. 
Iterator<I, T> I must have an operator== comparing two Is and returning a bool. 
I must have an operator!= comparing two Is and returning a bool. 
I must have a copy constructor. 
I must have an assignment operator. 
I must have an operation next() that moves to the next value in the 
sequence. 
I must have an operation get() that returns the current value (of type T).
Concepts 
// Requirements: Addable<T>, Assignable<T>, CopyConstructible<T>, 
// Iterator<I, T> 
template<typename I, typename T> 
T sum(I start, I end, T init); 
// Requirements: EqualityComparable<T>, Assignable<T>, 
// CopyConstructible<T>, Iterator<I, T> 
template<typename I, typename T> 
I find(I start, I end, T value);
Nested Requirements 
Concept Requirements 
Iterator<I, T> EqualityComparable<I>, CopyConstructible<I>, Assignable<I> 
I must have an operation next() that moves to the next value in the sequence. 
I must have an operation get() that returns the current value (of type T).
Associated Types 
Concept Requirements 
Iterator<I> EqualityComparable<I>, CopyConstructible<I>, Assignable<I> 
I must have an operation next() that moves to the next value in the sequence. 
value_type is an associated type, accessible via iterator_traits<I>::value_type 
I must have an operation get() that returns the current value (of type value_type). 
// Requirements: Iterator<I>, Addable<value_type>, 
// Assignable<value_type>, CopyConstructible<value_type> 
template<typename I> 
typename iterator_traits<T>::value_type 
sum(I start, I end, typename iterator_traits<T>::value_type init) { 
for (I current = start; current != end; current = next(current)) 
init = init + get(current); 
return init; 
} 
template<typename T> 
struct iterator_traits<T*> { typedef T value_type; };
Concept Refinement 
Concept Requirements 
BidirectionalIterator<I> Refines Iterator<I> 
I must have an operation prev() that moves to the previous value in the 
sequence. 
I must have an operation set() that sets the current value.
Specialization 
// Requirements: Polygon<P> 
template<typename P> 
double circumference(P p) { 
double result = 0; 
for (int i = 0; i < num_sides(p); ++i) 
result += side_length(p, i); 
return result; 
} 
// Requirements: EquilateralPolygon<P> 
template<typename P> 
double circumference(P p) { 
return num_sides(p) * side_length(p, 0); 
}
Anatomy of a Concept 
A concept is a set of requirements consisting of valid expressions, associated types, 
invariants, and complexity guarantees. A type that satisfies the requirements is 
said to model the concept. A concept can extend the requirements of another 
concept, which is called refinement. 
• Valid Expressions are C++ expressions which must compile successfully for the 
objects involved in the expression to be considered models of the concept. 
• Associated Types are types that are related to the modeling type in that they 
participate in one or more of the valid expressions. Typically associated types can be 
accessed either through typedefs nested within a class definition for the modeling 
type, or they are accessed through a traits class. 
• Invariants are run-time characteristics of the objects that must always be true, that 
is, the functions involving the objects must preserve these characteristics. The 
invariants often take the form of pre-conditions and post-conditions. 
• Complexity Guarantees are maximum limits on how long the execution of one of the 
valid expressions will take, or how much of various resources its computation will 
use.
Traits classes 
A traits class provides a way of associating information with a compile-time 
entity (a type, integral constant, or address) in non-intrusive (!!!) way 
template <class T> 
struct iterator_traits <T*>{ 
typedef random_access_iterator_tag iterator_category; 
typedef T value_type; 
typedef ptrdiff_t difference_type; 
typedef T* pointer; 
typedef T& reference; 
};
Tag Dispatching 
namespace std { 
struct input_iterator_tag { }; 
struct bidirectional_iterator_tag : input_iterator_tag { }; 
struct random_access_iterator_tag : bidirectional_iterator_tag { }; 
template <class InputIterator, class Distance> 
void advance(InputIterator& i, Distance n) { 
typename iterator_traits<InputIterator>::iterator_category category; 
detail::advance_dispatch(i, n, category); 
} 
}
Tag Dispatching 
namespace detail { 
template <class InputIterator, class Distance> 
void advance_dispatch(InputIterator& i, Distance n, input_iterator_tag ) { 
while (n--) ++i; 
} 
template <class BidirectionalIterator, class Distance> 
void advance_dispatch(BidirectionalIterator& i, Distance n, 
bidirectional_iterator_tag ) { 
if (n >= 0) 
while (n--) ++i; 
else 
while (n++) --i; 
} 
template <class RandomAccessIterator, class Distance> 
void advance_dispatch(RandomAccessIterator& i, Distance n, 
random_access_iterator_tag ) { 
i += n; 
}
Fragile C++ Templates 
template <class InputIterator, typename T> 
InputIterator find(InputIterator first, InputIterator beyond, 
const T& value) 
{ 
while (first < beyond && !(*first == value)) ++first; 
return first; 
}; 
std::vector<int> v; 
find(v.begin(), v.end(), 42); // Ok 
std::list<int> l; 
find(l.begin(), l.end(), 42); // error
Concepts for C++: Goals 
• Support for the core ideas of GP in C++ 
• Modular type checking for C++ templates 
• Performance equivalence to C++ templates 
• Complete backward compatibility 
• Simplicity 
• C++0x
Concepts Overview 
• Concepts definitions: Specify the behaviour 
of types via requirements 
• Where clauses: Specify constraints on 
template parameters in terms of concepts 
• Concept maps: Specify how types meet the 
requirements of concepts
Constrained Templates 
• Place constraints on template parameters via a 
where clause 
template <typename T> 
where LessThanComparable<T> 
const T& min(const T& x, const T& y) 
{ 
return x < y ? x : y; 
}
Concept Definitions 
• Concept definitions state requirements on type 
parameters 
concept LessThanComparable<typename T> { 
bool operator < (T, T); 
axiom Irreflexivity(T x) { !(x < x); } 
axiom Assymetry(T x, T y) { 
if (x < y) !(y < x); 
} 
axiom Transitivity(T x, T y, T z) { 
if (x < y && y < z) x < z; 
} 
}
Member Function Requirements 
concept CopyConstructable<typename T> { 
T::T(T const &); // copy constructor 
T::~T(); // desctructor 
}
Iterators and Nested Requirements 
concept InputIterator <typename Iter> { 
Iter& operator ++ (Iter&); 
Iter operator ++ (Iter&,int); 
bool operator == (Iter, Iter); 
bool operator != (Iter, Iter); 
???? operator * (Iter); 
};
Iterators and Nested Requirements 
concept InputIterator <typename Iter> { 
typename value_type; 
typename difference_type; 
where SignedIntergral<difference_type>; 
Iter& operator ++ (Iter&); 
Iter operator ++ (Iter&,int); 
bool operator == (Iter, Iter); 
bool operator != (Iter, Iter); 
value_type operator * (Iter); 
};
Using Associated Types 
template <class Iter, typename T> 
where 
InputIterator<Iter> && 
EqualityComparable<InputIterator<Iter>::value_type, T> 
Iter find(Iter first, Iter beyond, const T& value) 
{ 
while (first != beyond && !(*first == value)) 
++first; 
return first; 
};
Concept Maps 
bool contains(int const * array, int n, int value) { 
return find(array, array + n, value) != array + n; 
} 
• Concept maps satisfy concept constraints 
template <class T> 
concept_map InputIterator<T*> { 
typedef T value_type; 
typedef ptrdiff_t difference_type; 
}
Concept Refinement 
// A bidirectional iterator can move backward 
concept BidirectionalIterator<typename Iter> 
: InputIterator<Iter> 
{ 
Iter& operator -- (Iter&); 
Iter operator -- (Iter&, int); 
} 
// A random access iterator can jump around 
concept RandomIterator<typename Iter> 
: BidirectionalIterator<Iter> 
{ 
Iter operator + (Iter, difference_type); 
// ... 
}
Concept-based overloading 
template <InputIterator Iter> 
void advance(Iter & x, Iter::difference_type n) 
{ 
for (; n > 0; --n) ++x; // O(n) 
} 
template <RandomAccessIterator Iter> 
void advance(Iter & x, Iter::difference_type n) 
{ 
x += n; // O(1) 
}

Contenu connexe

Tendances

Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaGlenn Guden
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arraysHassan Dar
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In JavaSpotle.ai
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScriptRajat Saxena
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming languageMd.Al-imran Roton
 

Tendances (20)

Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Operators in java
Operators in javaOperators in java
Operators in java
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
Java threads
Java threadsJava threads
Java threads
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Generics in java
Generics in javaGenerics in java
Generics in java
 

En vedette (10)

C++ Templates 2
C++ Templates 2C++ Templates 2
C++ Templates 2
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Files in c++
Files in c++Files in c++
Files in c++
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
file handling c++
file handling c++file handling c++
file handling c++
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 

Similaire à Generic programming and concepts that should be in C++

Similaire à Generic programming and concepts that should be in C++ (20)

Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
overloading in C++
overloading in C++overloading in C++
overloading in C++
 
Functions1
Functions1Functions1
Functions1
 
Review functions
Review functionsReview functions
Review functions
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
UNIT3.pptx
UNIT3.pptxUNIT3.pptx
UNIT3.pptx
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
Savitch ch 17
Savitch ch 17Savitch ch 17
Savitch ch 17
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Function in c
Function in cFunction in c
Function in c
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Savitch Ch 17
Savitch Ch 17Savitch Ch 17
Savitch Ch 17
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Array Cont
Array ContArray Cont
Array Cont
 

Plus de Anton Kolotaev

Market microstructure simulator. Overview.
Market microstructure simulator. Overview.Market microstructure simulator. Overview.
Market microstructure simulator. Overview.Anton Kolotaev
 
FiQuant Market Microstructure Simulator (short version)
FiQuant Market Microstructure Simulator (short version)FiQuant Market Microstructure Simulator (short version)
FiQuant Market Microstructure Simulator (short version)Anton Kolotaev
 
FiQuant Market Microstructure Simulator: Strategy Definition Language
FiQuant Market Microstructure Simulator: Strategy Definition LanguageFiQuant Market Microstructure Simulator: Strategy Definition Language
FiQuant Market Microstructure Simulator: Strategy Definition LanguageAnton Kolotaev
 
Anton kolotaev. cv eng
Anton kolotaev. cv engAnton kolotaev. cv eng
Anton kolotaev. cv engAnton Kolotaev
 
FiQuant Market Simulator
FiQuant Market SimulatorFiQuant Market Simulator
FiQuant Market SimulatorAnton Kolotaev
 

Plus de Anton Kolotaev (6)

Market microstructure simulator. Overview.
Market microstructure simulator. Overview.Market microstructure simulator. Overview.
Market microstructure simulator. Overview.
 
FiQuant Market Microstructure Simulator (short version)
FiQuant Market Microstructure Simulator (short version)FiQuant Market Microstructure Simulator (short version)
FiQuant Market Microstructure Simulator (short version)
 
FiQuant Market Microstructure Simulator: Strategy Definition Language
FiQuant Market Microstructure Simulator: Strategy Definition LanguageFiQuant Market Microstructure Simulator: Strategy Definition Language
FiQuant Market Microstructure Simulator: Strategy Definition Language
 
Anton kolotaev. cv eng
Anton kolotaev. cv engAnton kolotaev. cv eng
Anton kolotaev. cv eng
 
Anton kolotaev. cv fr
Anton kolotaev. cv frAnton kolotaev. cv fr
Anton kolotaev. cv fr
 
FiQuant Market Simulator
FiQuant Market SimulatorFiQuant Market Simulator
FiQuant Market Simulator
 

Dernier

MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGSIVASHANKAR N
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 

Dernier (20)

MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 

Generic programming and concepts that should be in C++

  • 3. Generic Programming • Programming paradigm for developing efficient, reusable software libraries • Three primary tasks: • Categorize abstractions in a domain into concepts • Implement generic algorithms based on concepts • Build concrete models for the concepts
  • 4. Characteristics of Generic Libraries • Reusable: able to operate on user-defined types • Composable: able to operate on data types defined in another library • Efficient: performance on par with non-generic, hand-coded implementations
  • 5. Generic Programming Process 1. The Generic Programming process focuses on finding commonality among similar implementations of the same algorithm, then providing suitable abstractions in the form of concepts so that a single, generic algorithm can realize many concrete implementations. 2. This process, called lifting, is repeated until the generic algorithm has reached a suitable level of abstraction, where it provides maximal reusability without sacrificing performance. 3. Dual to the lifting process is specialization, which synthesizes efficient concrete implementations for particular uses of a generic algorithm. Only by balancing the lifting and specialization processes can we ensure that the resulting generic algorithms are both reusable and efficient.
  • 6. Lifting Basic Types int sum(int* array, int n) { int result = 0; for (int i = 0; i < n; ++i) result = result + array[i]; return result; } float sum(float* array, int n) { float result = 0; for (int i = 0; i < n; ++i) result = result + array[i]; return result; } template<typename T> T sum(T* array, int n) { T result = 0; for (int i = 0; i < n; ++i) result = result + array[i]; return result; }
  • 7. Lifting Basic Types std::string concatenate(std::string* array, int n) { std::string result = ""; for (int i = 0; i < n; ++i) result = result + array[i]; return result; } // Requirements: // T must have a default constructor that produces the identity value // T must have an additive operator + // T must have an assignment operator // T must have a copy constructor template<typename T> T sum(T* array, int n) { T result = T(); for (int i = 0; i < n; ++i) result = result + array[i]; return result;}
  • 8. Lifting Containers // Requirements: // T must have a default constructor that produces the identity // value // T must have an additive operator + // T must have an assignment operator // T must have a copy constructor // Container must have an indexing operator [] that returns a T template<typename Container, typename T> T sum(const Container& array, int n) { T result = T(); for (int i = 0; i < n; ++i) result = result + array[i]; return result; }
  • 9. Lifting Iteration template<typename T> struct list_node { list_node<T>* next; T value; }; struct linked_list { list_node<T>* start; }; template<typename T> T sum(list_node<T> list, int n) { T result = 0; for (list_node<T>* current = list.start; current != NULL; current = current->next) result = result + current->value; return result; }
  • 10. Lifting Iteration // Requirements: // T must have an additive operator + // T must have an assignment operator // T must have a copy constructor // I must have an inequality operator != // I must have a copy constructor // I must have an operation next() that moves to the next value in // the sequence // I must have an operation get() that returns the current value (of // type T). template<typename I, typename T> T sum(I start, I end, T init) { for (I current = start; current != end; current = next(current)) init = init + get(current); return init; }
  • 11. Concepts // Requirements: // T must have an equality operator == // T must have a copy constructor // I must have an inequality operator != // I must have a copy constructor // I must have an assignment operator // I must have an operation next() that moves to the next value in // the sequence // I must have an operation get() that returns the current value // (of type T). template<typename I, typename T> I find(I start, I end, T value) { for (I current = start; current != end; current = next(current)) if (get(current) == value) return current; return end; }
  • 12. Concepts Concept Requirements CopyConstructible<T> T must have a copy constructor Assignable<T> T must have an assignment operator Addable<T> T must have an operator+ that takes two T values and returns a T EqualityComparable<T> T must have an operator== comparing two Ts and returning a bool. T must have an operator!= comparing two Ts and returning a bool. Iterator<I, T> I must have an operator== comparing two Is and returning a bool. I must have an operator!= comparing two Is and returning a bool. I must have a copy constructor. I must have an assignment operator. I must have an operation next() that moves to the next value in the sequence. I must have an operation get() that returns the current value (of type T).
  • 13. Concepts // Requirements: Addable<T>, Assignable<T>, CopyConstructible<T>, // Iterator<I, T> template<typename I, typename T> T sum(I start, I end, T init); // Requirements: EqualityComparable<T>, Assignable<T>, // CopyConstructible<T>, Iterator<I, T> template<typename I, typename T> I find(I start, I end, T value);
  • 14. Nested Requirements Concept Requirements Iterator<I, T> EqualityComparable<I>, CopyConstructible<I>, Assignable<I> I must have an operation next() that moves to the next value in the sequence. I must have an operation get() that returns the current value (of type T).
  • 15. Associated Types Concept Requirements Iterator<I> EqualityComparable<I>, CopyConstructible<I>, Assignable<I> I must have an operation next() that moves to the next value in the sequence. value_type is an associated type, accessible via iterator_traits<I>::value_type I must have an operation get() that returns the current value (of type value_type). // Requirements: Iterator<I>, Addable<value_type>, // Assignable<value_type>, CopyConstructible<value_type> template<typename I> typename iterator_traits<T>::value_type sum(I start, I end, typename iterator_traits<T>::value_type init) { for (I current = start; current != end; current = next(current)) init = init + get(current); return init; } template<typename T> struct iterator_traits<T*> { typedef T value_type; };
  • 16. Concept Refinement Concept Requirements BidirectionalIterator<I> Refines Iterator<I> I must have an operation prev() that moves to the previous value in the sequence. I must have an operation set() that sets the current value.
  • 17. Specialization // Requirements: Polygon<P> template<typename P> double circumference(P p) { double result = 0; for (int i = 0; i < num_sides(p); ++i) result += side_length(p, i); return result; } // Requirements: EquilateralPolygon<P> template<typename P> double circumference(P p) { return num_sides(p) * side_length(p, 0); }
  • 18. Anatomy of a Concept A concept is a set of requirements consisting of valid expressions, associated types, invariants, and complexity guarantees. A type that satisfies the requirements is said to model the concept. A concept can extend the requirements of another concept, which is called refinement. • Valid Expressions are C++ expressions which must compile successfully for the objects involved in the expression to be considered models of the concept. • Associated Types are types that are related to the modeling type in that they participate in one or more of the valid expressions. Typically associated types can be accessed either through typedefs nested within a class definition for the modeling type, or they are accessed through a traits class. • Invariants are run-time characteristics of the objects that must always be true, that is, the functions involving the objects must preserve these characteristics. The invariants often take the form of pre-conditions and post-conditions. • Complexity Guarantees are maximum limits on how long the execution of one of the valid expressions will take, or how much of various resources its computation will use.
  • 19. Traits classes A traits class provides a way of associating information with a compile-time entity (a type, integral constant, or address) in non-intrusive (!!!) way template <class T> struct iterator_traits <T*>{ typedef random_access_iterator_tag iterator_category; typedef T value_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef T& reference; };
  • 20. Tag Dispatching namespace std { struct input_iterator_tag { }; struct bidirectional_iterator_tag : input_iterator_tag { }; struct random_access_iterator_tag : bidirectional_iterator_tag { }; template <class InputIterator, class Distance> void advance(InputIterator& i, Distance n) { typename iterator_traits<InputIterator>::iterator_category category; detail::advance_dispatch(i, n, category); } }
  • 21. Tag Dispatching namespace detail { template <class InputIterator, class Distance> void advance_dispatch(InputIterator& i, Distance n, input_iterator_tag ) { while (n--) ++i; } template <class BidirectionalIterator, class Distance> void advance_dispatch(BidirectionalIterator& i, Distance n, bidirectional_iterator_tag ) { if (n >= 0) while (n--) ++i; else while (n++) --i; } template <class RandomAccessIterator, class Distance> void advance_dispatch(RandomAccessIterator& i, Distance n, random_access_iterator_tag ) { i += n; }
  • 22. Fragile C++ Templates template <class InputIterator, typename T> InputIterator find(InputIterator first, InputIterator beyond, const T& value) { while (first < beyond && !(*first == value)) ++first; return first; }; std::vector<int> v; find(v.begin(), v.end(), 42); // Ok std::list<int> l; find(l.begin(), l.end(), 42); // error
  • 23. Concepts for C++: Goals • Support for the core ideas of GP in C++ • Modular type checking for C++ templates • Performance equivalence to C++ templates • Complete backward compatibility • Simplicity • C++0x
  • 24. Concepts Overview • Concepts definitions: Specify the behaviour of types via requirements • Where clauses: Specify constraints on template parameters in terms of concepts • Concept maps: Specify how types meet the requirements of concepts
  • 25. Constrained Templates • Place constraints on template parameters via a where clause template <typename T> where LessThanComparable<T> const T& min(const T& x, const T& y) { return x < y ? x : y; }
  • 26. Concept Definitions • Concept definitions state requirements on type parameters concept LessThanComparable<typename T> { bool operator < (T, T); axiom Irreflexivity(T x) { !(x < x); } axiom Assymetry(T x, T y) { if (x < y) !(y < x); } axiom Transitivity(T x, T y, T z) { if (x < y && y < z) x < z; } }
  • 27. Member Function Requirements concept CopyConstructable<typename T> { T::T(T const &); // copy constructor T::~T(); // desctructor }
  • 28. Iterators and Nested Requirements concept InputIterator <typename Iter> { Iter& operator ++ (Iter&); Iter operator ++ (Iter&,int); bool operator == (Iter, Iter); bool operator != (Iter, Iter); ???? operator * (Iter); };
  • 29. Iterators and Nested Requirements concept InputIterator <typename Iter> { typename value_type; typename difference_type; where SignedIntergral<difference_type>; Iter& operator ++ (Iter&); Iter operator ++ (Iter&,int); bool operator == (Iter, Iter); bool operator != (Iter, Iter); value_type operator * (Iter); };
  • 30. Using Associated Types template <class Iter, typename T> where InputIterator<Iter> && EqualityComparable<InputIterator<Iter>::value_type, T> Iter find(Iter first, Iter beyond, const T& value) { while (first != beyond && !(*first == value)) ++first; return first; };
  • 31. Concept Maps bool contains(int const * array, int n, int value) { return find(array, array + n, value) != array + n; } • Concept maps satisfy concept constraints template <class T> concept_map InputIterator<T*> { typedef T value_type; typedef ptrdiff_t difference_type; }
  • 32. Concept Refinement // A bidirectional iterator can move backward concept BidirectionalIterator<typename Iter> : InputIterator<Iter> { Iter& operator -- (Iter&); Iter operator -- (Iter&, int); } // A random access iterator can jump around concept RandomIterator<typename Iter> : BidirectionalIterator<Iter> { Iter operator + (Iter, difference_type); // ... }
  • 33. Concept-based overloading template <InputIterator Iter> void advance(Iter & x, Iter::difference_type n) { for (; n > 0; --n) ++x; // O(n) } template <RandomAccessIterator Iter> void advance(Iter & x, Iter::difference_type n) { x += n; // O(1) }