+ All Categories
Home > Documents > GPCE'04, Vancouver 1 Towards a General Template Introspection Library in C++ István Zólyomi,...

GPCE'04, Vancouver 1 Towards a General Template Introspection Library in C++ István Zólyomi,...

Date post: 03-Jan-2016
Category:
Upload: philippa-pope
View: 214 times
Download: 0 times
Share this document with a friend
Popular Tags:
27
GPCE'04, Vancouv GPCE'04, Vancouv er er 1 Towards a General Towards a General Template Introspection Template Introspection Library in C++ Library in C++ István István Z Z ólyomi ólyomi , Zolt , Zolt án Porkoláb án Porkoláb Department of Programming Languages Department of Programming Languages and and Compilers Compilers Eötvös Loránd University, Budapest, Hungar Eötvös Loránd University, Budapest, Hungar y y {scamel, gsd}@elte.hu {scamel, gsd}@elte.hu
Transcript
Page 1: 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.

GPCE'04, VancouverGPCE'04, Vancouver 11

Towards a General Towards a General Template Introspection Template Introspection

Library in C++Library in C++

István István ZZólyomiólyomi, Zolt, Zoltán Porkolábán PorkolábDepartment of Programming LanguagesDepartment of Programming Languages and and

CompilersCompilers

Eötvös Loránd University, Budapest, HungarEötvös Loránd University, Budapest, Hungaryy

{scamel, gsd}@elte.hu{scamel, gsd}@elte.hu

Page 2: 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.

GPCE'04, VancouverGPCE'04, Vancouver 22

C++ TemplatesC++ Templates

Provides language support for Provides language support for parametric polymorphismparametric polymorphism

““Type-aware smart macros”Type-aware smart macros” Many checks are delayed until instantiationMany checks are delayed until instantiation No restrictions on parametersNo restrictions on parameters

Templates alone form a Turing-complete Templates alone form a Turing-complete functional language inside C++functional language inside C++ Based on template specializationsBased on template specializations

Page 3: 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.

GPCE'04, VancouverGPCE'04, Vancouver 33

Issues on TemplatesIssues on Templates Lazy evaluation: instantiate template Lazy evaluation: instantiate template

members only on requestmembers only on request Wider scale of parameters supportedWider scale of parameters supported Avoid code bloatAvoid code bloat Unexpected late errorsUnexpected late errors Hard to decode error messagesHard to decode error messages

Classic example:Classic example: Member function of a class template using Member function of a class template using srot()srot() instead of instead of sort()sort() compiles compiles

Compile error when Compile error when callingcalling member member functionfunction

Page 4: 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.

GPCE'04, VancouverGPCE'04, Vancouver 44

IntrospectionIntrospection

Entity can observe its own stateEntity 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 compilerInformation gained from compiler Direct language supportDirect language support Hand written exploitsHand written exploits

Page 5: 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.

GPCE'04, VancouverGPCE'04, Vancouver 55

Introspection in C++Introspection in C++

Limited direct support in the languageLimited direct support in the language sizeofsizeof

Would be useful toWould be useful to Make restrictions on template Make restrictions on template

parameters (concept checking)parameters (concept checking) Extend current type system (generate Extend current type system (generate

conversions, operations)conversions, operations) Optimization (e.g. expression templates)Optimization (e.g. expression templates)

Page 6: 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.

GPCE'04, VancouverGPCE'04, Vancouver 66

Compile-time AdaptationCompile-time Adaptation

A program can observe its stateA program can observe its state May make decisions depending on stateMay make decisions depending on state

Data structuresData structures Implementation strategiesImplementation strategies

Template metaprogramming, e.g. boost::mplTemplate metaprogramming, e.g. boost::mpl E.g. a container decide to store:E.g. a container decide to store:

Comparable values in binary treeComparable values in binary tree Other values in listOther values in list

Compiler rules apply for generated programCompiler rules apply for generated program

Page 7: 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.

GPCE'04, VancouverGPCE'04, Vancouver 77

Concept CheckingConcept Checking

Concept: list of requirements on a typeConcept: list of requirements on a type Enforce concepts on template Enforce concepts on template

parameters immediately at parameters immediately at instantiationinstantiation

Improve implementation qualityImprove implementation quality Especially useful at the STL, e.g. for Especially useful at the STL, e.g. for

iterator categoriesiterator categories

Page 8: 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.

GPCE'04, VancouverGPCE'04, Vancouver 88

Concept Checking in Other Concept Checking in Other LanguagesLanguages

Parameter type must implement Parameter type must implement interface or derive from base classinterface or derive from base class

JavaJavainterface Sortable { ... }interface Sortable { ... }class SortedList <T extends Sortable> ...class SortedList <T extends Sortable> ...

EiffelEiffelclass SORTED_LIST [T -> COMPARABLE] ...class SORTED_LIST [T -> COMPARABLE] ...

Similar in functional languagesSimilar in functional languages

Page 9: 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.

GPCE'04, VancouverGPCE'04, Vancouver 99

Concept Checking in Other Concept Checking in Other LanguagesLanguages

Ada: generic interface, no inheritance Ada: generic interface, no inheritance requiredrequired

genericgeneric --- Element type--- Element type type T is private;type T is private; --- Comparision on element type--- Comparision on element type with function “<“ (X,Y: T) return boolean is <>;with function “<“ (X,Y: T) return boolean is <>;package Sorted_Listpackage Sorted_List ......endend

--- Generics are instantiated explicitly--- Generics are instantiated explicitlypackage SL is new Sorted_List(MyType, “<=“);package SL is new Sorted_List(MyType, “<=“);

Page 10: 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.

GPCE'04, VancouverGPCE'04, Vancouver 1010

Concept Checking Concept Checking TechniquesTechniques

Currently used in C++:Currently used in C++: require (GNU STL)require (GNU STL) boost::concept_checkboost::concept_check

ShortagesShortages No elementary conditions identifiedNo elementary conditions identified No orthogonalityNo orthogonality No composition:No composition:

““Fulfill or die” philosophyFulfill or die” philosophy Implicit conjunctionImplicit conjunction

No cooperation with other librariesNo cooperation with other libraries

Page 11: 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.

GPCE'04, VancouverGPCE'04, Vancouver 1111

Ideal Concept Checking Ideal Concept Checking LibraryLibrary

Compile time “execution”Compile time “execution” Identifying elementary conditionsIdentifying elementary conditions Orthogonal designOrthogonal design Boolean results instead of aborting Boolean results instead of aborting

compilationcompilation Condition compositionCondition composition Cooperation with metaprogramming librariesCooperation with metaprogramming libraries Something like an extension to Something like an extension to boost::type_traitsboost::type_traits for concept checkingfor concept checking

Page 12: 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.

GPCE'04, VancouverGPCE'04, Vancouver 1212

GoalsGoals Implement introspection library to Implement introspection library to

enable concept checking that is close to enable concept checking that is close to idealideal

Cooperation with metaprogramming Cooperation with metaprogramming libraries (e.g. libraries (e.g. boost::mplboost::mpl))

Use only standard C++Use only standard C++ No language extensionNo language extension No typeof operatorNo typeof operator No compiler-specific featuresNo compiler-specific features

No external tools (e.g. No external tools (e.g. gcc-xmlgcc-xml))

Page 13: 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.

GPCE'04, VancouverGPCE'04, Vancouver 1313

Programming Programming TTechniquesechniques

EllipseEllipse: accept any parameter: accept any parametervvoid foid f(...);(...);

Function overloadFunction overloadYes isOk(ExpectedType); // expected caseYes isOk(ExpectedType); // expected case

No isOk(...); // rescue caseNo isOk(...); // rescue case

Return types have different sizesReturn types have different sizesstruct No { char dummy; };struct No { char dummy; };

struct Yes { char dummy[2]; };struct Yes { char dummy[2]; };

Page 14: 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.

GPCE'04, VancouverGPCE'04, Vancouver 1414

Programming TechniquesProgramming Techniques

Map return types to boolean valuesMap return types to boolean valuessizeof( isOk(expression) ) == sizeof(Yes);sizeof( isOk(expression) ) == sizeof(Yes);

Convenience macro for mappingConvenience macro for mapping// --- The same with macro shortcut// --- The same with macro shortcut

bool res = CONFORMS( isOk(expression) );bool res = CONFORMS( isOk(expression) );

Page 15: 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.

GPCE'04, VancouverGPCE'04, Vancouver 1515

Programming TechniquesProgramming Techniques

boost::enable_if boost::enable_if // --- Enabled case// --- Enabled case

template <bool b, class T>template <bool b, class T>

struct enable_if { typedef T Result; };struct enable_if { typedef T Result; };

// --- Specialized disabled case// --- Specialized disabled case

template <class T>template <class T>

struct enable_if<false> {};struct enable_if<false> {};

Page 16: 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.

GPCE'04, VancouverGPCE'04, Vancouver 1616

Programming TechniquesProgramming Techniques

SFINAE ruleSFINAE rule(Substitution failure is not an error)(Substitution failure is not an error)

// --- Expected case for T// --- Expected case for Tenable_if<sizeof(T::Feature), Yes> f(T&);enable_if<sizeof(T::Feature), Yes> f(T&);

// --- Rescue case// --- Rescue caseNo f(...);No f(...);

bool res = CONFORMS( f(Type()) );bool res = CONFORMS( f(Type()) );

Page 17: 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.

GPCE'04, VancouverGPCE'04, Vancouver 1717

Elementary ConditionsElementary Conditions

Checks implemented forChecks implemented for Existence of embedded type with Existence of embedded type with namename Existence of class Existence of class member with member with namename Exact type of embedded typeExact type of embedded type Exact type of member (both function Exact type of member (both function

and data)and data)

Page 18: 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.

GPCE'04, VancouverGPCE'04, Vancouver 1818

Embedded Type NameEmbedded Type Name Inspect if type has an embedded Inspect if type has an embedded

type with given nametype with given name Need macrosNeed macros

PREPARE_TYPE_CHECKER(iterator);PREPARE_TYPE_CHECKER(iterator);......// --- Look for name ‘iterator’ in T// --- Look for name ‘iterator’ in Tconst const bool res bool res = CONFORMS(= CONFORMS(

TYPE_IN_CLASS(iterator, T)TYPE_IN_CLASS(iterator, T)););

Page 19: 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.

GPCE'04, VancouverGPCE'04, Vancouver 1919

Member NameMember Name Inspect if type has a non-type Inspect if type has a non-type

member (either data or function) with member (either data or function) with given namegiven name

Similar to previous conditionSimilar to previous condition

PREPARE_MEMBER_CHECKER(size);PREPARE_MEMBER_CHECKER(size);......// --- Look for member ‘size’ in T// --- Look for member ‘size’ in Tconst bool res = CONFORMS(const bool res = CONFORMS(

MEMBER_IN_CLASS(size, T)MEMBER_IN_CLASS(size, T)););

Page 20: 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.

GPCE'04, VancouverGPCE'04, Vancouver 2020

Nested TypeNested Type

Inspect nested type if name existsInspect nested type if name exists Cooperate with other tools, e.g. Cooperate with other tools, e.g. boost::type_traitsboost::type_traits

// --- Inspect traits of nested type// --- Inspect traits of nested type

const bool isScalar = const bool isScalar = type_traits<T::value_type>::is_scalar;type_traits<T::value_type>::is_scalar;

// --- Inspect exact type// --- Inspect exact type

const bool isInteger =const bool isInteger =

SameTypes<int, T::value_type>::Result;SameTypes<int, T::value_type>::Result;

Page 21: 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.

GPCE'04, VancouverGPCE'04, Vancouver 2121

MembersMembers Exact type of member if name existsExact type of member if name exists

// --- Inspect if ‘size’ is data member// --- Inspect if ‘size’ is data member

const bool isDataMember = CONFORMS(const bool isDataMember = CONFORMS(

Member<unsigned int>::NonStatic( &T::size )Member<unsigned int>::NonStatic( &T::size )

););

// --- Inspect if ‘size’ is member function// --- Inspect if ‘size’ is member function

typedef unsigned int Fun() const;typedef unsigned int Fun() const;

const bool isMemberFunction = CONFORMS(const bool isMemberFunction = CONFORMS(

Member<Fun>::NonStatic( &T::size )Member<Fun>::NonStatic( &T::size )

););

Page 22: 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.

GPCE'04, VancouverGPCE'04, Vancouver 2222

Composite ConditionsComposite Conditions

User can easily assemble complex conditionsUser can easily assemble complex conditions

template <class T> struct LessThanComparabletemplate <class T> struct LessThanComparable{{

enum { Conforms =enum { Conforms =CONFORMS( Function<bool (const T&, const T&)>::CONFORMS( Function<bool (const T&, const T&)>::

Static( &::operator< )Static( &::operator< )||||

CONFORMS( Function<bool (const T&) const>::CONFORMS( Function<bool (const T&) const>::NonStatic( &T::operator< )NonStatic( &T::operator< )

};};};};

Page 23: 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.

GPCE'04, VancouverGPCE'04, Vancouver 2323

Hacking?Hacking?

Two opinions:Two opinions: Should be language extensionShould be language extension Should be user codeShould be user code

Language changeLanguage change Major issueMajor issue Must have proved designMust have proved design Should be based on previous Should be based on previous

experiencesexperiences

Page 24: 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.

GPCE'04, VancouverGPCE'04, Vancouver 2424

Open QuestionsOpen Questions

What is the minimal orthogonal set of What is the minimal orthogonal set of conditions?conditions?

What other conditions are expected What other conditions are expected to be implemented?to be implemented?

What conditions are What conditions are theoreticallytheoretically impossible to implement with current impossible to implement with current language standard?language standard? DefaultConstructableDefaultConstructable??

Page 25: 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.

GPCE'04, VancouverGPCE'04, Vancouver 2525

SummarySummary Separation of introspection from Separation of introspection from

intercessionintercession Implemented elementary conditionsImplemented elementary conditions Observation provides compile time Observation provides compile time boolbool Easy to define new user conditionsEasy to define new user conditions Arbitrary combination of conditions is possibleArbitrary combination of conditions is possible

And, or, negateAnd, or, negate Specialization on this result is possibleSpecialization on this result is possible

Supports compile-time adaptationSupports compile-time adaptation Supports concept checkingSupports concept checking

Page 26: 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.

GPCE'04, VancouverGPCE'04, Vancouver 2626

Further PlansFurther Plans

Implement more elementary Implement more elementary conditionsconditions

Check theorethical limitation of Check theorethical limitation of implementationimplementation

Implement a concept-checking Implement a concept-checking library usable in the STLlibrary usable in the STL

Page 27: 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.

GPCE'04, VancouverGPCE'04, Vancouver 2727

Thank You!Thank You!

See related material See related material atathttp://gsd.web.elte.huhttp://gsd.web.elte.hu


Recommended