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.

Slides:



Advertisements
Similar presentations
1 An anomaly of subtype relations at component refinement and a generative solution in C++ Zoltán Porkoláb, István Zólyomi {gsd | Eötvös.
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.
5th MaCS Debrecen On the Turing-Completeness of Generative Metaprograms Zoltán Porkoláb, István Zólyomi Dept. of Programming.
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Abstract Data Types and Encapsulation Concepts
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.
Language Evaluation Criteria
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
1 An extension to the subtype relationship in C++ István Zólyomi, Zoltán Porkoláb and Tamás Kozsik {scamel | gsd | Eötvös Loránd University,
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
CS 355 – Programming Languages
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Sumant Tambe, et. al LEESA DSPD 2008 An Embedded Declarative Language for Hierarchical Object Structure Traversal Sumant Tambe* Aniruddha Gokhale Vanderbilt.
Ceg860 (Prasad)L6MR1 Modularity Extendibility Reusability.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Templates ~ their instantiation and specialization.
Generic Programming Johan Torp. Agenda GP introduction GP in perspective Questions * GP = Generic programming in C++
Compiler Support for Profiling C++ Template Metaprograms József Mihalicza, Norbert Pataki, Zoltán Porkoláb Eötvös Loránd University Faculty of Informatics.
C++ Template Metaprogramming Why, When and How? Zoltán Porkoláb Dept. of Programming Languages and Compilers, Faculty of Informatics Eötvös.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Templates.
CNS  Executive Overview  Template Parameters  Function Template Issues 2 CNS Templates.
Metaprogramming from University to Industry Zoltán Porkoláb Dept. of Programming Languages and Compilers, Faculty of.
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++
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
CS212: Object Oriented Analysis and Design Lecture 9: Function Overloading in C++
(c) 2004, Eric Niebler FOR_EACH by Eric Niebler or, How I Learned to Stop Worrying and Love the Preprocessor.
1 A Comparative Study Of Language Support for Generic Programming Oopsla 2003 Roland Garcia Jaakko Jarvi Andrew Lumsdaine Jeremy Siek Jeremiah Wilcock.
Meta IFL 2007 Freiburg1 Meta - Towards a Functional-Style Interface for C++ Template Metaprograms * Ádám Sipos, Zoltán Porkoláb, Norbert Pataki, Viktória.
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
CS212: Object Oriented Analysis and Design
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Overview of C++ Templates
3C-1 Purity Typing Language semantics Inheritance model  Single vs. Multiple inheritance  Common root Modular mechanisms Generics Object Oriented Languages.
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
C++ Inheritance Data Structures & OO Development I 1 Computer Science Dept Va Tech June 2007 © McQuain Generalization versus Abstraction Abstraction:simplify.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
Inheritance and Composition Reusing the code and functionality Unit - 04.
Concepts in C++. Templates in current C++ C++ template is typeless No language support for constrained generics Accidental errors found in instantiation.
1 CS Programming Languages Class 22 November 14, 2000.
Template Lecture 11 Course Name: High Level Programming Language Year : 2010.
PROGRAMMING TECHNIQUES Based on “Modern C++ Design” BY ALEXANDRESCU BOGDAN PENKOVSKY 2010.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
Classes - Part II (revisited) n Constant objects and member functions n Definition Form of Member Functions n friend functions and friend classes n Constructors.
M.Sc. Seminar - Keren Lenz Supervisor - Dr. Yossi Gil July 1 st 2007 Simple and Safe SQL Queries with C++ Templates A RA R AT -
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (this Friday). Today: –Templates. –STL –Smart Pointers.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
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.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
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.
Csontos Péter, Porkoláb Zoltán Eötvös Loránd Tudományegyetem, Budapest ECOOP 2001 On the complexity of exception handling.
ISBN Chapter 12 Support for Object-Oriented Programming.
CSC 520 – Advanced Object Oriented Programming, Fall, 2010 Thursday, September 30 Week 5, Generics and Inheritance Techniques, Meyer Ch. 10 & 16.
5th MaCS Debrecen On the Turing-Completeness of Generative Metaprograms Zoltán Porkoláb, István Zólyomi Dept. of Programming.
Abstract Data Types and Encapsulation Concepts
Type Traits By Reggie Meisler.
Overview of C++ Overloading
Abstract Types Defined as Classes of Variables
Presentation transcript:

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 Eötvös Loránd University, Budapest, Hungary {scamel,

GPCE'04, Vancouver2 C++ Templates Provides language support for parametric polymorphism Provides language support for parametric polymorphism “Type-aware smart macros” “Type-aware smart macros” Many checks are delayed until instantiation Many checks are delayed until instantiation No restrictions on parameters No restrictions on parameters Templates alone form a Turing-complete functional language inside C++ Templates alone form a Turing-complete functional language inside C++ Based on template specializations Based on template specializations

GPCE'04, Vancouver3 Issues on Templates Lazy evaluation: instantiate template members only on request Lazy evaluation: instantiate template members only on request Wider scale of parameters supported Wider scale of parameters supported Avoid code bloat Avoid code bloat Unexpected late errors Unexpected late errors Hard to decode error messages Hard to decode error messages Classic example: Classic example: Member function of a class template using srot() instead of sort() compiles Member function of a class template using srot() instead of sort() compiles Compile error when calling member function Compile error when calling member function

GPCE'04, Vancouver4 Introspection Entity can observe its own state Entity can observe its own state Information gained in runtime from: Information gained in runtime from: Interpreter (Perl, Ruby, etc) Interpreter (Perl, Ruby, etc) VM (Java,.Net, etc) VM (Java,.Net, etc) Environment (C++ RTTI) Environment (C++ RTTI) Information gained from compiler Information gained from compiler Direct language support Direct language support Hand written exploits Hand written exploits

GPCE'04, Vancouver5 Introspection in C++ Limited direct support in the language Limited direct support in the language sizeof sizeof Would be useful to Would be useful to Make restrictions on template parameters (concept checking) Make restrictions on template parameters (concept checking) Extend current type system (generate conversions, operations) Extend current type system (generate conversions, operations) Optimization (e.g. expression templates) Optimization (e.g. expression templates)

GPCE'04, Vancouver6 Compile-time Adaptation A program can observe its state A program can observe its state May make decisions depending on state May make decisions depending on state Data structures Data structures Implementation strategies Implementation strategies Template metaprogramming, e.g. boost::mpl Template metaprogramming, e.g. boost::mpl E.g. a container decide to store: E.g. a container decide to store: Comparable values in binary tree Comparable values in binary tree Other values in list Other values in list Compiler rules apply for generated program Compiler rules apply for generated program

GPCE'04, Vancouver7 Concept Checking Concept: list of requirements on a type Concept: list of requirements on a type Enforce concepts on template parameters immediately at instantiation Enforce concepts on template parameters immediately at instantiation Improve implementation quality Improve implementation quality Especially useful at the STL, e.g. for iterator categories Especially useful at the STL, e.g. for iterator categories

GPCE'04, Vancouver8 Concept Checking in Other Languages Parameter type must implement interface or derive from base class Parameter type must implement interface or derive from base class Java Java interface Sortable {... } class SortedList... Eiffel Eiffel class SORTED_LIST [T -> COMPARABLE]... Similar in functional languages Similar in functional languages

GPCE'04, Vancouver9 Concept Checking in Other Languages Ada: generic interface, no inheritance required Ada: generic interface, no inheritance requiredgeneric --- Element type --- Element type type T is private; type T is private; --- Comparision on element type --- Comparision on element type with function “ ; with function “ ; package Sorted_List......end --- Generics are instantiated explicitly package SL is new Sorted_List(MyType, “<=“);

GPCE'04, Vancouver10 Concept Checking Techniques Currently used in C++: Currently used in C++: require (GNU STL) require (GNU STL) boost::concept_check boost::concept_check Shortages Shortages No elementary conditions identified No elementary conditions identified No orthogonality No orthogonality No composition: No composition: “Fulfill or die” philosophy “Fulfill or die” philosophy Implicit conjunction Implicit conjunction No cooperation with other libraries No cooperation with other libraries

GPCE'04, Vancouver11 Ideal Concept Checking Library Compile time “execution” Compile time “execution” Identifying elementary conditions Identifying elementary conditions Orthogonal design Orthogonal design Boolean results instead of aborting compilation Boolean results instead of aborting compilation Condition composition Condition composition Cooperation with metaprogramming libraries Cooperation with metaprogramming libraries Something like an extension to boost::type_traits for concept checking Something like an extension to boost::type_traits for concept checking

GPCE'04, Vancouver12 Goals Implement introspection library to enable concept checking that is close to ideal Implement introspection library to enable concept checking that is close to ideal Cooperation with metaprogramming libraries (e.g. boost::mpl ) Cooperation with metaprogramming libraries (e.g. boost::mpl ) Use only standard C++ Use only standard C++ No language extension No language extension No typeof operator No typeof operator No compiler-specific features No compiler-specific features No external tools (e.g. gcc-xml ) No external tools (e.g. gcc-xml )

GPCE'04, Vancouver13 Programming Techniques Ellipse: accept any parameter Ellipse: accept any parameter void f(...); Function overload Function overload Yes isOk(ExpectedType); // expected case No isOk(...); // rescue case Return types have different sizes Return types have different sizes struct No { char dummy; }; struct Yes { char dummy[2]; };

GPCE'04, Vancouver14 Programming Techniques Map return types to boolean values Map return types to boolean values sizeof( isOk(expression) ) == sizeof(Yes); Convenience macro for mapping Convenience macro for mapping // --- The same with macro shortcut bool res = CONFORMS( isOk(expression) );

GPCE'04, Vancouver15 Programming Techniques boost::enable_if boost::enable_if // --- Enabled case template template struct enable_if { typedef T Result; }; // --- Specialized disabled case template template struct enable_if {};

GPCE'04, Vancouver16 Programming Techniques SFINAE rule (Substitution failure is not an error) SFINAE rule (Substitution failure is not an error) // --- Expected case for T enable_if f(T&); // --- Rescue case No f(...); bool res = CONFORMS( f(Type()) );

GPCE'04, Vancouver17 Elementary Conditions Checks implemented for Checks implemented for Existence of embedded type with name Existence of embedded type with name Existence of class member with name Existence of class member with name Exact type of embedded type Exact type of embedded type Exact type of member (both function and data) Exact type of member (both function and data)

GPCE'04, Vancouver18 Embedded Type Name Inspect if type has an embedded type with given name Inspect if type has an embedded type with given name Need macros Need macrosPREPARE_TYPE_CHECKER(iterator);... // --- Look for name ‘iterator’ in T const bool res = CONFORMS( TYPE_IN_CLASS(iterator, T) );

GPCE'04, Vancouver19 Member Name Inspect if type has a non-type member (either data or function) with given name Inspect if type has a non-type member (either data or function) with given name Similar to previous condition Similar to previous conditionPREPARE_MEMBER_CHECKER(size);... // --- Look for member ‘size’ in T const bool res = CONFORMS( MEMBER_IN_CLASS(size, T) );

GPCE'04, Vancouver20 Nested Type Inspect nested type if name exists Inspect nested type if name exists Cooperate with other tools, e.g. boost::type_traits Cooperate with other tools, e.g. boost::type_traits // --- Inspect traits of nested type const bool isScalar = type_traits ::is_scalar; // --- Inspect exact type const bool isInteger = SameTypes ::Result;

GPCE'04, Vancouver21 Members Exact type of member if name exists Exact type of member if name exists // --- Inspect if ‘size’ is data member const bool isDataMember = CONFORMS( Member ::NonStatic( &T::size ) ); // --- Inspect if ‘size’ is member function typedef unsigned int Fun() const; const bool isMemberFunction = CONFORMS( Member ::NonStatic( &T::size ) );

GPCE'04, Vancouver22 Composite Conditions User can easily assemble complex conditions User can easily assemble complex conditions template struct LessThanComparable { enum { Conforms = CONFORMS( Function :: Static( &::operator :: Static( &::operator< )|| CONFORMS( Function :: NonStatic( &T::operator :: NonStatic( &T::operator< )};};

GPCE'04, Vancouver23 Hacking? Two opinions: Two opinions: Should be language extension Should be language extension Should be user code Should be user code Language change Language change Major issue Major issue Must have proved design Must have proved design Should be based on previous experiences Should be based on previous experiences

GPCE'04, Vancouver24 Open Questions What is the minimal orthogonal set of conditions? What is the minimal orthogonal set of conditions? What other conditions are expected to be implemented? What other conditions are expected to be implemented? What conditions are theoretically impossible to implement with current language standard? What conditions are theoretically impossible to implement with current language standard? DefaultConstructable ? DefaultConstructable ?

GPCE'04, Vancouver25 Summary Separation of introspection from intercession Separation of introspection from intercession Implemented elementary conditions Implemented elementary conditions Observation provides compile time bool Observation provides compile time bool Easy to define new user conditions Easy to define new user conditions Arbitrary combination of conditions is possible Arbitrary combination of conditions is possible And, or, negate And, or, negate Specialization on this result is possible Specialization on this result is possible Supports compile-time adaptation Supports compile-time adaptation Supports concept checking Supports concept checking

GPCE'04, Vancouver26 Further Plans Implement more elementary conditions Implement more elementary conditions Check theorethical limitation of implementation Check theorethical limitation of implementation Implement a concept-checking library usable in the STL Implement a concept-checking library usable in the STL

GPCE'04, Vancouver 27 Thank You! See related material at