Generic Programming Johan Torp. Agenda GP introduction GP in perspective Questions * GP = Generic programming in C++

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
1 STL and Its Design Principles Alexander Stepanov.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
1 Objects and ClassesStefan Kluth 1.6Objects and Classes 1.6What is an Object? 1.7Objects and Classes 1.8Object Interface, Class Inheritance, Polymorphism.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
 2006 Pearson Education, Inc. All rights reserved Templates.
C++ Training Datascope Lawrence D’Antonio Lecture 3 An Overview of C++
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles C/C++ Emery Berger and Mark Corner University of Massachusetts.
 2006 Pearson Education, Inc. All rights reserved. Templates (again)CS-2303, C-Term Templates (again) CS-2303 System Programming Concepts (Slides.
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Generative Programming. Generic vs Generative Generic Programming focuses on representing families of domain concepts Generic Programming focuses on representing.
C++ fundamentals.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
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++ 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.
Polymorphism in C++ 24th Aug Overview Polymorphism means “Many forms” OO Purists – “Only virtual methods” Liberal C++ guys – Either virtual methods.
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.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
Higher order programming Using C++ and boost. C++ concepts // T must model MyFuncConcept template generic_function(T t) { t.MyFunc(); }
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Generative Programming. Automated Assembly Lines.
Programming Language Support for Generic Libraries Jeremy Siek and Walid Taha Abstract The generic programming methodology is revolutionizing the way we.
OOP Class Lawrence D’Antonio Lecture 3 An Overview of C++
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.
Programming in Java CSCI-2220 Object Oriented Programming.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Overview of C++ Templates
Object Oriented Programming
3C-1 Purity Typing Language semantics Inheritance model  Single vs. Multiple inheritance  Common root Modular mechanisms Generics Object Oriented Languages.
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Copyright © 2005 Elsevier Object-Oriented Programming Control or PROCESS abstraction is a very old idea (subroutines!), though few languages provide it.
Introduction to Object-Oriented Programming Lesson 2.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
Concepts in C++. Templates in current C++ C++ template is typeless No language support for constrained generics Accidental errors found in instantiation.
Modern C++ in practice.
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) ICS 313: Programming Language Theory Chapter 11: Abstract Data Types (Data Abstraction)
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
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)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Lecture 2 Intro. To Software Engineering and Object-Oriented Programming (2/2)
Generic Programming and Library Design Brian Bartman
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
ECE 750 Topic 8 Meta-programming languages, systems, and applications Automatic Program Specialization for J ava – U. P. Schultz, J. L. Lawall, C. Consel.
 2006 Pearson Education, Inc. All rights reserved Templates.
CSC 520 – Advanced Object Oriented Programming, Fall, 2010 Thursday, September 30 Week 5, Generics and Inheritance Techniques, Meyer Ch. 10 & 16.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
5th MaCS Debrecen On the Turing-Completeness of Generative Metaprograms Zoltán Porkoláb, István Zólyomi Dept. of Programming.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
7. Inheritance and Polymorphism
Object-Oriented Programming (OOP) Lecture No. 45
Multi-Methods in Cecil
CSE687 - Object Oriented Design class notes Survey of the C++ Programming Language Jim Fawcett Spring 2004.
About the Presentations
Object-Orientated Programming
Types of Programming Languages
Built-In (a.k.a. Native) Types in C++
CSE341: Programming Languages Section 9 Dynamic Dispatch Manually in Racket Zach Tatlock Winter 2018.
Presentation transcript:

Generic Programming Johan Torp

Agenda GP introduction GP in perspective Questions * GP = Generic programming in C++

What is GP? Algorithmic GP GP techniques & patterns in C++

Polymorphism class BarInterface { virtual void bar() = 0; }; void polymorphicFunction(BarInterface& t) {... t.bar();... } template void polymorphicFunction(T& t) {... t.bar();... }

GP interface is called concept // MyBarConcept // // Has a memberfunction called bar() //... more assumptions... // T must fulfill MyBarConcept template void polymorphicFunction1(T& bar); // T must fulfill MyBarConcept template void polymorphicFunction200(T& bar); class MyBar { void bar(); };

Example concepts Concept DefaultConstructible Copyable Assignable Addable Convertible to OtherType OutputStreamable BarConcept Valid expressions T t; T t2(t1); t1 = t2 t1+t2; static_cast (t); stream << t; t.bar(); Require as little as possible for maximal genericity

Concepts are type requirements Valid expressions, pre/post conditions & semantics Additionally: Invariants, associated types, complexity guarantees, etc Concepts in C++ are expressed in documentation Types which fulfill concept C are said to model C Refine new concepts from old ones by adding additional requirements

Input Iterator Description An Input Iterator is an iterator that may be dereferenced to refer to... Refinement of Trivial Iterator Associated Types Value type - The type obtained by dereferencing... Distance type - A signed integral type used to... Valid expressions Dereference *i Pre-increment ++i Expression semantics Dereference Will return a reference to the accessed value type Pre-increment Will... Complexity guarantees All operations are amortized constant time

Template instantiation class OneBar { void bar() }; class AnotherBar { void bar() }; Source1.cpp: polymorphicFunction(int(123)); Source2.cpp: polymorphicFunction(OneBar()); polymorphicFunction(OneBar()); polymorphicFunction(AnotherBar()); Source3.cpp: polymorphicFunction(OneBar());

Generalize memcpy void* memcpy(void* region1, const void* region2,size_t n); Only reads contigous memory Only writes to contigous memory Only byte-wise copying

Minimal requirements of copying traverse through source sequence access source elements copy elements to destination know when to stop

STL version of copy template OutputIterator copy(InputIterator first, InputIterator pastLast, OutputIterator result) { while (!(first == pastLast)) // Don't require != operator *result++ = *first++; return result; }

How pointless?! Real std::copy is optimized for different types Solves optimized generic copying once and for all

C++ language features supporting GP Dispatching features Inheritance Templates Namespaces & argument dependent lookup (ADL) Function & operator overloading Implicit type conversion SFINAE [Partial] template specialization Other useful language features Dependent types Template type deduction Template non-type arguments (compile-time integers, bools, etc) Template template arguments

GP techniques & patterns type traits mix-in classes policy based design object generators enable if tag dispatching type erasure lazy data views concept and archetype checking GP related programming models: template metaprogramming expression templates to create DSELs macro metaprogramming

GP in practice Generalize patterns / boiler plate into generic classes Library based programming models

GP problems Compilation & link time Code size Language flaws

How much GP can we afford? Maybe we can use more GP because: Compilers have improved Well modularized => recompile less Master/unity builds lessens template bloat Stability & higher abstraction level allows faster iteration too Explicit template instantiation can lessen template bloat Replacing boilerplate interfaces with type erasure gives similar run-time performance

GP flaws fixed in C++0x Concept code support True variadic templates Type deduction and type inference of named variables Rvalue references Preventing template instantiation Axioms Object construction improvements... and lots more! Compilers are continously adding C++0x features

GP vs OOP: Efficiency and compilation GP more efficient run-time OO code requires less compilation

GP vs OOP: Dependencies Concrete OO classes and polymorphic code are coupled via the interface A type might fulfill/model a concept. Polymorphic code only depends on concept via documentation A.k.a. : ad-hoc polymorphism vs parametric polymorphism

GP vs OOP: Customization points Mix-in classes change interface, state, data layout, etc template class Foo : public MixIn {...}; Type traits & tags can non-intrusively add static information template struct iterator_traits { typedef random_access_iterator_tag iterator_category;};

GP vs OOP: Orthogonality template class TweakableGPClass{... }; class TweakableOOClass{ TweakableOOClass(Aspect1&, Aspect2&, Aspect3&); private: Aspect1& m_a1;... }; Composition problems Boiler-plate Run-time costs (vtable calls, method forwarding, extra state)

GP vs OOP: Dispatch OOP is only polymorphic on one type - the object type GP is polymorphic on all parameter types GP also allow complex dispatch logic! // Default fallback, unless no other function matches better template void handleCollision(Object1&, Object2&); // Any object going into a black hole disappears template void handleCollision(Object1&, BlackHole&); // Unless it's another black hole -- then we get // a super nova explosion instead. Yay! template<> void handleCollision(BlackHole&, BlackHole&); // Missiles which hit anything damagable inflicts damage template enable_if ::value> handleCollision(Missile&, Object2&);

GP vs OOP: Simplicity More power = more ways to shoot ourselves in the foot OO is less abstract GP is best suited to build generic libraries - which in turn provide simple and limited programming models

C++ multiparadigm programming Object orientation Generic programming Procedural programming

GP and dynamically typed languages def foo(t): """t must model bar"""... t.bar()... Compiled separately, extremely fast iteration time Late binding can provide poor runtime performance Nothing checked statically, rely on interpreters & unit tests

A reflection on reflection Reflection allows a program to observe and modify its own structure and behavior at runtime GP dispatch techniques are similar to run-time reflection GP allows static analysis => understandable behaviour

GP is generative Macro > Template instantiation > Compilation Work on multiple "compilation levels" in the same file at the same time

Code generation Raise abstraction level without runtime penalty Pay in terms of build system complexity Identify boiler plate & patterns and generate them

Summary Concepts are type requirements Template instantiation Algorithmic GP GP techniques GP problems GP classes are highly customizable and reusable GP vs OOP GP is useful for core libraries & algorithms Dynamic programming languages & reflection Code generation

Questions?