/
DesignofConceptLibrariesforC++AndrewSuttonandBjarneStroustrupTexasA&MU DesignofConceptLibrariesforC++AndrewSuttonandBjarneStroustrupTexasA&MU

DesignofConceptLibrariesforC++AndrewSuttonandBjarneStroustrupTexasA&MU - PDF document

conchita-marotz
conchita-marotz . @conchita-marotz
Follow
371 views
Uploaded On 2016-03-08

DesignofConceptLibrariesforC++AndrewSuttonandBjarneStroustrupTexasA&MU - PPT Presentation

InthisworkweexperimentwithdesignsforconceptsbytryingtominimizethenumberofconceptsrequiredtoconstrainthegenericalgorithmsanddatastructuresofalibraryTodosuchexperimentsweneedwaystorepresentconceptsin ID: 246857

Inthiswork weexperimentwithdesignsforconceptsbytryingtominimizethenumberofconceptsrequiredtoconstrainthegenericalgorithmsanddatastructuresofalibrary.Todosuchexperiments weneedwaystorepresentconceptsin

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "DesignofConceptLibrariesforC++AndrewSutt..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

DesignofConceptLibrariesforC++AndrewSuttonandBjarneStroustrupTexasA&MUniversityDepartmentofComputerScienceandEngineering{asutton,bs}@cse.tamu.eduAbstract.Wepresentasetofconcepts(requirementsontemplatearguments)foralargesubsetoftheISOC++standardlibrary.Thegoalofourworkistwofold:toidentifyaminimalandusefulsetofconceptsrequiredtoconstrainthelibrary'sgenericalgorithmsanddatastructuresandtogaininsightsintohowbesttosupportsuchconceptswithinC++.Westartwiththedesignofconceptsratherthanthedesignofsupportinglanguagefeatures;thelanguagedesignmustbemadetottheconcepts,ratherthantheotherwayaround.Adirectresultoftheexperimentistherealizationthattosimplyandelegantlysupportgenericpro-grammingweneedtwokindsofabstractions:constraintsarepredicatesonstaticpropertiesofatype,andconceptsareabstractspecicationsofanalgorithm'ssyntacticandsemanticrequirements.Constraintsarenecessarybuildingblocksofconcepts.Semanticpropertiesarerepresentedasaxioms.Wesummarizeourapproach:concepts=constraints+axioms.Thisinsightisleveragedtode-velopalibrarycontainingonly14conceptsthatencompassingthefunctional,iterator,andalgorithmcomponentsoftheC++StandardLibrary(theSTL).TheconceptsareimplementedasconstraintclassesandevaluatedusingClang'sandGCC'sStandardLibrarytestsuites.Keywords:Genericprogramming,concepts,constraints,axioms,C++.1IntroductionConcepts(requirementsontemplatearguments)arethecentralfeatureofC++genericlibrarydesign;theydenethetermsinwhichalibrary'sgenericdatastructuresandalgorithmsarespecied.Everyworkinggenericlibraryisbasedonconcepts.Theseconceptsmayberepresentedusingspecicallydesignedlanguagefeatures(e.g.[15,20]),inrequirementstables(e.g.,[2,22]),ascommentsinthecode,indesigndocuments(e.g.,[21]),orsimplyintheheadsofprogrammers.However,withoutconcepts(formalorinformal),nogenericcodecouldwork.Forexample,aMatrixlibrarythatallowsausertosupplyelementtypesmusthaveaconceptofwhatoperationscanbeusedonitselements.Inotherwords,theMatrixli-braryhasaconceptofa“number,”whichhasadefactodenitionintermsofoperationsusedinthelibrarycode.Interpretationsof“number”canvarydramaticallyfromlibrarytolibrary.Isapolynomialfunctionanumber'?Arenumberssupposedtosupportdivi-sion?Areoperationsonnumberssupposedtobeassociative?Regardless,everygenericMatrixlibraryhasa“number”concept. Inthiswork,weexperimentwithdesignsforconceptsbytryingtominimizethenumberofconceptsrequiredtoconstrainthegenericalgorithmsanddatastructuresofalibrary.Todosuchexperiments,weneedwaystorepresentconceptsinC++code.Ourapproachistouseconstraintclasses,whichallowsustoexperimentwithdifferentsetsofconceptsforalibrarywithoutpre-judgingtheneedsforspeciclanguagesupportfeatures.Oncewehaveexperimentedwiththedesignofconceptsforseverallibraries,weexpectourcriteriaforconceptdesignandusetohavematuredtothepointwherewecancondentlyselectamongthereasonablywell-understoodlanguagedesignalter-natives.Languagesupportshouldbedeterminedbyidealusagepatternsratherthantheotherwayaround.Previousworkinthedevelopmentofconceptlibrarieshasresultedinthedenitionoflargenumbersofconceptstoconstraincomparativelyfewgenericcomponents.Forexample,thelastversionoftheC++DraftStandardtoincludeconcepts[5]dened130conceptstoconstrainapproximately250datastructuresandalgorithms.Nearly2/3rdsofthatlibrary'sexportedabstractionswereconceptdenitions.Outofthe130concepts,108relateareusedto(directlyorindirectly)expressthefunctional,iterator,andalgorithmspartsofthestandardlibrarythatweaddresshere.Incomparison,theElementsofProgramming(EoP)book[34]coverssimilarmaterialwith52conceptsforabout180differentalgorithms(justunder1/3rd).Obviously,notalloftheconceptsineitherpublicationare“equallyabstract”.ThatC++DraftStandardincludesabout30conceptsenumeratingrequirementsonoverload-ableoperator`saloneandseveralmetaprogramming-likeconceptssuchasRvalue_of.TheEoPbooklistsmanyconceptsthatexplorevariationsonatheme;invariantsarestrengthenedorweakened,operatorsaredropped,anddenitionspacesarerestricted.Fromtheseandsimilardesignsofconcepts,ithasbeenconcludedthatwritingagenericlibraryrequiresexhaustiveenumerationofoverloadableoperations,conceptualsupportfortemplatemetaprogramming,andmassivedirectlanguagesupportforconcepts.Fortunately,suchconclusionsarefalse.Furthermore,theyareobviouslyfalse.Theoverwhelmingmajorityofgenericlibraries,includingtheoriginalversionofSTL,werewrittenwithoutlanguagesupportforconceptsandusedwithoutenforcementmecha-nisms.Theauthorsoftheselibrariesdidnotconsidersomehundreddifferentconceptsduringtheirdevelopment.Rather,thegenericcomponentsoftheselibrarieswerewrit-tentoasmallsetofidealizedabstractions.Wearguethatgenericlibrariesaredenedintermsofsmallsetsofabstractandintuitiveconcepts,andthataneffectivespecicationofconceptsistheproductofaniterativeprocessthatminimizesthenumberofconceptswhilemaintainingexpressiveandeffectiveconstraints.Idealconceptsarefundamentaltotheirapplicationdomain(e.g.,String,Number,andIterator),andconsequentlyitisarareachievementtondagenuinenewone.Theseabstractandintuitiveconceptsmustnotbelostinthedetailsneededtoexpressthemincode.Neithershouldtheeaseoflearningandeaseofuseofferedbytheseconceptsbecompromisedbyanefforttominimizetheconstraintsofeveryalgorithm.Toexploretheseideasconcretely,wedevelopaminimaldesignoftheconceptsfortheSTLthatencompassesitsfunctional,iterator,andalgorithmlibraries.Theresultingconceptlibrarydenesonly14concepts,94fewerthanoriginallyproposedforthecor- respondingpartsoftheC++StandardLibrary.WeleveragetheresultsoftheexperimentandtheexperiencegainedtoderiveanovelperspectiveonconceptsfortheC++pro-gramminglanguage.Ourapproachrevealsadistinctdifferencebetweenrequirementsthatrepresentdomainabstractionsandthosethatsupporttheirspecication:conceptsandconstraints,respectively.Conceptsbasedonthisdistinctionresultsinaconceptu-allysimplerandmoremodulardesign.WevalidatethedesignoftheconceptsbyimplementingthemwithintheframeworkofaconceptemulationlibraryfortheOriginC++Libraries[38].Thelibrariesareim-plementedusingthe2011ISOC++standardfacilities.TheconceptsarethenintegratedintotheSTLsubsetofClang'slibc++andGCC'slibstdc++andcheckedagainsttheirtestsuitesforvalidation.Theresultsofthisworkyieldseveralcontributionstoourknowledgeofgenericpro-gramming.First,wedemonstratethatitisbothfeasibleanddesirabletoexperimenttoseekaminimalconceptualspecicationforagenericlibrary.Second,wedemonstratethatdistinguishingbetweenconcepts(asabstractions)andconstraints(asstaticrequire-ments)isaneffectivewaytoachievethisgoal.Third,weidentifysemanticproperties,axioms,asthekeytopracticaldiscriminationofconceptsfromconstraints.Finally,weprovideasimplerandeasiertousespecicationofkeypartsoftheISOC++standardlibrary.2RelatedWorkGenericprogrammingisrootedintheabilitytospecifycodethatwillworkwithava-rietyoftypes.Everylanguagesupportinggenericprogrammingmustaddresstheissueofhowtospecifytheinterfacebetweengenericallywrittencodeandthesetofconcretetypesonwhichitoperates.Severalcomparativestudieshavebeenconductedinsupportforgenericprogrammingandtypeconstraints[18].ThesestudieswereleveragedtosupportthedenitionofconceptsforC++MLreliesonsignaturestospecifytheinterfaceofmodulesandconstrainthetypeparametersoffunctors[27].Operationsinthesignaturearematchedagainstthosede-nedbyastructuretodetermineconformance.InHaskell,typeclassesdenotesetsoftypesthatcanbeusedwithsameoperations[24].Atypeismadeamemberofthatsetbyexplicitlydeclaringitaninstanceandimplementingtherequisiteoperations.Typeclassesareusedasconstraintsontypeparametersinthesignaturesofpolymor-phicfunctions.SimilaritiesbetweenHaskelltypeclassesandC++conceptshavealsobeenexplored[6,7].AXIOMcategoriesareusedtodenethesyntaxandsemanticsofalgebraicdomains[10].Thespecicationofalgebraicstructureshelpedmotivatethedesignofitscategorysystem[9,11].RequirementsontypeparametersinEiffel,Java,andC#arespeciedintermsofinheritedinterfaces.Checkingtheconformanceofasuppliedtypeargumententailsdeterminingifitisasubtypeoftherequiredinterfaceorclass[8,25,26,41].FromtheearliestdaysofthedesignofC++templates,peoplehavebeenlookingforwaystospecifyandconstraintemplatearguments[35,36].FortheC++0xstan-dardsefforttwoproposals(withmanyvariants)wereconsidered[15,20].Alanguageframeworksupportinggenericprogrammingwasdevelopedinsupportofthesepropos-als[32,33]. Therehasbeenlessworkonthedesignofconceptsthemselves(asopposedtostudyinglanguagesupport).Thedominantphilosophyofconceptdesignhasfocusedon“lifting”algorithmsfromspecicimplementationstogenericalgorithmswithspecicrequirementsonarguments[28].However,applyingthesameprocesstotheconcepts(iterativegeneralization)canleadtoanexplosioninthenumberofconceptsasrequire-mentsareminimizedforeachalgorithminisolation.The(ultimatelyunsuccessful)de-signforC++0xincludedacarefullycraftedandtesteddesignforthecompleteC++0xstandardlibraryincludingaround130concepts[5].In[13],DehnertandStepanovde-nedpropertiesofregulartypesandfunctions.StepanovandMcJonescarefullyworkedoutasetofconceptsfortheirvariantoftheSTLinEoP[34];DosReisimplementedvericationforthoseandfoundafewimprovements[14].Otherresearchhasfocusedontheuseofconceptsortheirexpressioninsourcecode.BaggeandHaveraaenexploredtheuseofaxiomstosupporttestingandthesemanticspecicationofalgebraicconcepts[4].Pirkelbaueretal[29]andSuttonandMaletic[40]studiedconceptsthroughmechanismsforautomaticallyextractingrequirementsfromactualsourcecode.Also,manyaspectsofconceptscanberealizedidiomaticallyinC++0x[12,39];thisisthebasisofourimplementationinthiswork.3RequirementsforConceptDesignTheimmediateandlong-termgoalsofthisresearcharetodevelopanunderstandingoftheprinciplesofconceptsandtoformulatepracticalguidelinesfortheirdesign.Amidtermgoalistoapplythatunderstandingtothedesignoflanguagefeaturestosupporttheuseofconcepts,especiallyinC++.Here,wepresentanexperimentinwhichweseekaconceptualspecicationfortheSTLthatdenesaminimumnumberofconcepts.Thisgoalisinstarkcontrasttopreviouswork[5]wheretheexplicitrepresentationofeventhesubtlestdistinctionsinrequirementswastheideal.Theminimizationaspectoftheexperimentconstrainsthedesigninsuchawaythattheresultingconceptsmustbeabstractandexpressive.Aconceptrepresentsagenericalgorithm'srequirementsonatypesuchasaNumberoranIterator.Aconceptisapredicatethatcanbeappliedtoatypetoascertainifitmeetstherequirementsembodiedbytheconcept.Anexpressiveconcept,suchasIterator,allowsabroadrangeofrelatedexpressionsonavarietyoftypes.Incontrast,asimplesyntacticrequirement,suchasrequiringdefaultconstruction,isaconstraintonimplementersanddoesnotexpressageneralconcept.Theeffectofthisminimizationiseaseoflearningandeaseuse.Inparticular,itprovideslibrarydesignersanduserswithasimple,strongdesignguidelinethatcouldneverbeachievedwith(say)100primitiverequirements(primitiveinthemathematicalsense).Thedesignofaconceptlibraryistheresultoftwominimizationproblems:conceptandconstraintminimization.Conceptminimizationseekstondthesmallestsetofconceptsthatadequatelyrep-resenttheabstractionsofagenericlibrary.Theproblemisna?velysolvedbydeningasingleconceptthatsatisestherequirementsofalltemplates.Forexample,mutablerandom-accessiteratorsworkwithpracticallyallSTLalgorithmssoaminimumcon-ceptspecicationmightsimplybeaRandom_access_iterator.Thiswouldresultin over-constrainedtemplatesandmakemanyreal-worldusesinfeasible.Forexample,alinked-listcannoteasilyandeconomicallysupportrandomaccessandaninputstreamcannotsupportrandomaccessatall.Conversely,thepopularobject-orientednotionofauniversalObjecttypeunder-constrainsinterfaces,sothatprogrammershavetorelyonruntimeresolution,runtimeerrorhandling,andexplicittypeconversion.Constraintminimizationseekstondasetofconstraintsthatminimallyconstrainthetemplatearguments.Thisproblemisna?velysolvedbynamingtheminimalsetoftyperequirementsfortheimplementationofanalgorithm.Iftwoalgorithmshavenon-identicalbutoverlappingsetsofrequirements,wefactoroutthecommonparts,whichresultsinthreelogicallyminimalsetsofrequirements.Thisprocessisrepeatedforallalgorithmsinalibrary.Conceptsdevelopedinthismannerresemblethesyntacticcon-structsfromwhichtheyarederived;thenumberofconceptsisequaltothenumberofuniquelytypedexpressionsinasetofthealgorithms.Thisresultsinthetotalabsenceofabstractionandlargenumbersofirregular,non-intuitiveconcepts.Intheextreme,everyimplementationofeveryalgorithmneedsitsownconcept,thusnegatingthepur-poseof“concepts”bymakingthemnothingbutarestatementoftherequirementsofaparticularpieceofcode.Effectiveconceptdesignsolvesbothproblemsthroughaprocessofiterativerene-ment.Aninitial,minimalsetofconceptsisdened.Templatesareanalyzedforre-quirements.Iftheinitialsetofconceptsproducesoverlystrictconstraints,theconceptdenitionsmustberefactoredtoweakentheconstraintsonthetemplate'sarguments.However,theconceptsmustnotberefactoredtotheextentthattheynolongerrepresentintuitiveandpotentiallystableabstractions.4Concepts=Constraints+AxiomsPreviousworkonconceptsuseasinglelanguagemechanismtosupportboththeab-stractinterfaces(representedtousersasconcepts)andthequeriesabouttypepropertiesneededtoeliminateredundancyinconceptimplementations.Fromalanguage-technicalpointofview,thatmakessense,butitobscuresthefundamentaldistinctionbetweeninterfaceandimplementationofrequirements.Worse,itdiscouragestheprogrammerfrommakingthisdistinctionbynotprovidinglanguagetoexpressthedistinction.Weconcludethatweneedseparatemechanismsforthedenitionofconceptsandfortheirimplementation.Weconsiderthreeformsoftemplaterequirementsinourdesign:–Constraintsdenethestaticallyevaluablepredicatesonthepropertiesandsyntaxoftypes,butdonotrepresentcohesiveabstractions.–Axiomsstatesemanticrequirementsontypesthatshouldnotbestaticallyevaluated.Anaxiomisaninvariantthatisassumedtohold(asopposedrequiredtobechecked)fortypesthatmeetaconcept.–Conceptsarepredicatesthatrepresentgeneral,abstract,andstablerequirementsofgenericalgorithmsontheirargument.Theyaredenedintermsofconstraintsandaxioms.Constraintsarecloselyrelatedtothenotionoftypetraits,metafunctionsthatevalu-atethepropertiesoftypes.Wechoosetheterm“constraint”over“trait”becauseofthe variedsemanticsalreadyassociatedtheword“trait.”Theword“constraint”alsoem-phasizesthecheckablenatureofthespecications.Theterms“concept”and“axiom”arewellestablishedintheC++community[1,2,5,16,18,22,34,39].Constraintsandaxiomsarethebuildingblocksofconcepts.Constraintscanbeusedtostaticallyquerytheproperties,interfaces,andrelationshipsoftypesandhavedirectanalogsintheStandardLibraryastypetraits(e.g.,is_const,is_constructible,is_-same).Infact,amajorityoftheconceptsinC++0xrepresentconstraints[5].Axiomsspecifythemeaningofthoseinterfacesandrelationships,typeinvariants,andcomplexityguarantees.PreviousrepresentationsofconceptsinC++deneaxiomsasfeaturesexpressedwithinconcepts[5,16].Inourmodel,weallowaxiomstobewrit-tenoutsideofconceptspecications,notunlikepropertiesintheEoPbook[34].Thisallowsustodistinguishbetweensemanticsthatareinherenttothemeaningofaconceptandthosethatcanbestatedasassumedbyaparticularalgorithm.Thedistinctionalsoallowsustorecombinesemanticpropertiesofconceptswithoutgeneratinglatticesofsemanticallyorthogonalconcepts,whichresultsindesignswith(potentiallyfar)fewerconcepts.Thedistinctivepropertythatseparatesaconceptfromaconstraintisthatithassemanticproperties.Inotherwords,wecanwriteaxiomsforaconcept,butdoingsoforaconstraintwouldbefarfetched.Thisdistinctionis(obviously)semanticsoitispossibletobeuncertainabouttheclassicationofapredicate,butwendthatafterawhiletheclassicationbecomescleartodomainexperts.Inseveralcases,theefforttoclassifydeepenedourunderstandingoftheabstractionandinfourcasesthe“canwestateanaxiom?”criterionchangedtheclassicationofapredicate,yielding—inretrospect—abetterdesign.Theseimprovementsbasedontheuseofaxiomswereinadditiontothedramaticsimplicationswehadachievedusingourearlier(lessprecise)criteriaofabstractnessandgenerality.Ourdecisiontodifferentiateconceptsandconstraintswasnotmadelightly,norwasthedecisiontoallowaxiomstobedecoupledfromconcepts.Thesedecisionsaretheresultofiterativelyrening,balancing,andtuningconceptsfortheSTLsubjecttotheconstraintsoftheexperiment.Theseinsights,oncemade,haveresultedinaclear,concise,andremarkablyconsistentviewoftheabstractionsintheSTL.Thedistinctionbetweenconcepts,constraints,andaxiomsisavaluablenewdesigntoolthatsupportsmodularityandreuseinconceptualspecications.Weexpectthedistinctiontohaveimplicationsonthedesignofthelanguagesupportforconcepts.Forexample,ifweneedexplicitmodelingstatements(conceptmaps[20];whichisbynomeanscertain),theywouldonlybeneededforconcepts.Conversely,manyconstraintsarecompilerintrinsic[22].Thesetwodifferencesallowforsimplercompilationmodelandimprovedcompiletimescomparedtodesignsbasedonasinglelanguageconstruct[5,19].Asanexampleofthedifference,considertheC++0xconceptsHasPlus,HasMi-nus,HasMultiply,andHasDivide.Byourdenition,thesearenotconcepts.Theyarenothingbutrequirementsthatatypehasabinaryoperator+,-,*,and,/,respectively.Nomeaning(semantics)canbeascribedtoeachinisolation.Noalgorithmcouldbewrittenbasedsolelyontherequirementofanargumenttypeproviding(say)-and*.Incontrast,wecandeneaconceptthatrequiresacombinationofthose(say,allofthem) withtheusualsemanticsofarithmeticoperationsconventionallyandpreciselystatedasaxioms.Suchconceptsarethebasisformostnumericalgorithms.Itisfairlycommonforconstraintstorequirejustasingleoperationandforacon-cepttorequireseveralconstraintswithdenedsemanticrelationshipsamongthem.However,itisquitefeasibletohaveasingle-operationconceptand,conversely,amulti-operationconstraint.Forexample,considertheinterfacetobalancingoperationsfromaframeworkforbalanced-binarytreeimplementations[3]:constraintBalancer&#xtype;&#xname;&#x-278;Node{voidadd_xup(Node*);voidtouch(Node*);voiddetach(Node*);}Thisspeciesthethreefunctionsthatabalancerneedstosupplytobeusedbytheframework.Itisclearlyaninternalinterfaceoflittlegeneralityorabstraction;itisanimplementationdetail.Ifwetriedhardenough,wemightcomeupwithsomesemanticspecication(whichwoulddependonthesemanticsofNode),butitwouldbeunlikelytobeofuseoutsidethisparticularframework(whereitisusedinexactlyoneplace).Furthermore,itwouldbemostunlikelytosurviveamajorrevisionandextensionoftheframeworkunchanged.Inotherwords,thelackofgeneralityandthedifcultyofspecifyingsemanticrulesarestrongindicationsthatBalancerisnotageneralconcept,sowemakeitaconstraint.ItisconceivablethatinthefuturewewillunderstandtheapplicationdomainwellenoughtosupportastableandformallydenednotionofaBalancerandthen(andonlythen)wouldwepromoteBalancertoaconceptbyaddingthenecessaryaxioms.Partly,thedistinctionbetweenconceptandconstraintisoneofmaturityofapplicationdomain.Constraintsalsohelpaconceptdesignaccommodateirregularity.Anirregulartypeisonethatalmostmeetsrequirementsbutdeviatessothataconceptcannotbewrittentoexpressauniformabstractionthatincorporatestheirregulartype.Forexample,os-tream_iteratorand ool;vectorareirregularinthattheirvaluetypecannotbededucedfromtheirreferencetype.Expressiontemplatesareparagonsofirregularity:theyencodefragmentsofanabstractsyntaxtreeastypesandcansupportlazyevalu-ationwithoutadditionalsyntax[42].Wecan'tsupporteverysuchirregularitywithoutcreatingamessof“concepts”thatlackpropersemanticspecicationandarenotstable(becausetheyessentiallyrepresentimplementationdetails).However,suchirregularit-eratorsandexpressiontemplatesareviabletypeargumentstomanySTLalgorithms.Constraintscanbeusedtohidetheseirregularities,thussimplifyingthespecicationofconcepts.Along-termsolutionwillhavetoinvolvecleaner(probablymoreconstrained)specicationofalgorithms.5ConceptsfortheSTLOurconceptdesignfortheSTLiscomprisedofonly14concepts,17supportingcon-straints,and4independentaxioms.ThesearesummarizedinTable1.Wepresenttheconcepts,constraints,andaxiomsinthelibraryusingsyntaxsimilartothatdevelopedforC++0x[5,15,20].Thesyntaxusedinthispresentationcanbemappeddirectlyontotheimplementation,whichsupportsourvalidationmethod.Also, Table1.Concepts,constraints,andaxioms Concepts Constraints Regularity Iterators Operators Language Comparable Iterator Equal SameOrdered Forward_iterator Less CommonCopyable Bidirectional_iterator Logical_and DerivedMovable Random_access_iterator Logical_or ConvertibleRegular Logical_not Signed_int Callable Functional Types Initialization Other Function Boolean Destructible ProcedureOperation Constructible Input_iteratorPredicate Assignable Output_iteratorRelation Axioms Equivalence_relationStrict_weak_orderStrict_total_orderBoolean_algebra theconceptandconstraintnamesarewrittenaswethinktheyshouldappearwhenusedwithlanguagesupport,notastheyappearintheOriginlibrary.TodistinguishC++frompurelyobject-orientedorpurelyfunctionaltypesystems,weprefacethepresentationoftheseconceptswithasummaryviewofvaluesandob-jectswithinthecontextoftheC++typesystem.Inbrief,avalueisanabstract,im-mutableelementsuchasthenumber5orthecolorred.Anobjectresidesinaspecicareaofmemory(hasidentity)andmayholdavalue.InC++,valuesarerepresentedbyrvalues:literals,temporaries,andconstantexpressions(constexprvalues).Objectsarelvaluesthatsupportmutabilityintheformsofassignmentandmove(i.e.,variables).Objectsareuniquelyidentiedbytheiraddress.AconstantoftheformconstTisanobjectthatbehaveslikeavalueinthatitisimmutable,althoughitstillhasidentity.Areferenceisanaliastoanunderlyingvalue(rvaluereference)orobject(lvaluerefer-ence).Inorderforourdesigntobeconsideredviable,itmustaddressthedifferencesbetweenthevariouskindsoftypesintheC++typesystem[37].5.1RegularTypesInourdesign,allabstracttypesarerootedinthenotionofregularity.TheconceptReg-ularappearsinsomeformorotherinallformalizationsofC++types[22,32,34];itexpressesthenotionthatanobjectisfundamentallywellbehaved,e.g.itcanbecon-structed,destroyed,copied,andcomparedtootherobjectsofitstype.Also,Regulartypescanbeusedtodeneobjects.Regularityisthefoundationofthevalue-orientedsemanticsusedintheSTL,andisrootedinfournotions:Comparability,Order,Mov-ability,andCopyability.Theirrepresentationasconceptsfollow.conceptComparable&#xtype;&#xname;&#x-278;T{requiresconstraint&#xT000;Equal//syntaxofequalityrequiresaxiomEquiv&#xT000;alence_relation&#xT000;T;//semanticsofequivalencetemplate&#xPred;&#xicat;-27;耀P axiomEquality(Tx,Ty,Pp){x==y�=p(x)==p(y);//ifx==ythenforanyPredicatep,p(x)==p(y)}axiomInequality(Tx,Ty){(x!=y)==!(x==y);//inequalityisthenegationofequality}}TheComparableconceptdenesthenotionofequalitycomparisonforitstypear-gument.Itrequiresanoperator==viatheconstraintEqual,andthemeaningofthatoperatorisimposedbytheaxiomEquivalence_relation.TheEqualityaxiomdenestheactualmeaningofequality,namelythattwovaluesareequalif,foranyPredicate,theresultofitsapplicationisequal.WeusetheC++0xaxiomsyntaxwiththe�=(im-plies)operatoradded[16].TheInequalityaxiomconnectsthemeaningofequalitytoinequality.Ifatypedenes==butdoesnotacorresponding!=,wecanautomaticallygenerateacanonicaldenitionaccordingtothisaxiom(asdescribedinSect.6).TheInequalityaxiomrequiresthatuser-dened!=operatorsprovidethecorrectsemantics.WedenethenotionofOrdersimilarly:conceptOrdered&#xRegu;&#xlar-;➀T{requiresconstraint&#xT000;LessrequiresaxiomStrict_total_or&#xT000;der&#xT000;T;requiresaxiom&#xT000;Greaterrequiresaxiom&#xT000;Less_equalrequiresaxiom&#xT000;Greater_equal}Wefactorouttheaxiomsjusttoshowthatwecan,andbecausetheyareexamplesofaxiomsthatmightndmultipleuses:template&#xtype;&#xname;&#x-278;TaxiomGreater(Tx,Ty){&#xtype;&#xname;&#x-278;(xy)==(y)}template&#xtype;&#xname;&#x-278;TaxiomLess_equal(Tx,Ty){(x)==!(y)}template&#xtype;&#xname;&#x-278;TaxiomGreater_equal(Tx,Ty){&#xtype;&#xname;&#x-278;(x=y)==!(x)}AswithComparable,thedenitionofrequirementsispredicatedonasyntacticconstraint(Less)andasemanticrequirement(Strict_total_order).Obviously,notalltypesinherentlydeneatotalorder;IEEE754oatingpointvaluesdeneonlyapartialorderwhenconsideringNaNvalues.Becausethisisanaxiomandcan'tbeprovenbyaC++compiler,weareallowedtoassumethatitholds.Therequiredaxiomsconnectthemeaningoftheotherrelationaloperationsto. conceptCopyablele omp; rab;ကT{requiresconstraintDestructib&#xT000;le&&Constructibleconst&#xT,-2;砀T&axiomCopy_equality(Tx,Ty){x==y&#xT,-2;砀=T{x}==y&&x==y;//copyconstructioncopies(non-destructively)}};ACopyabletypeisbothcopyconstructibleandComparable.TheCopy_equalityaxiomstatesthatacopyofanobjectisequaltoitsoriginal.Copyable(andalsoMov-able)typesmustbeDestructible,ensuringthattheprogramcandestroytheconstructedobjects.conceptMovable&#xtype;&#xname;&#x-278;T{requiresconstraintDestructib&#xT000;le&&Constructible&#xT,-2;砀T&&axiomMove_effect(Tx,Ty){x==y&#xT,-2;砀=T{move(x)}==y&&can_destroy(x);//originalisvalidbutunspecied}}AMovabletypeismoveconstructible.Movinganobjectputsthemoved-fromob-jectinavalidbutunspeciedstate.TheC++0xaxiomsyntaxprovidesnowayofex-pressing“validbutunspecied”soweintroducetheprimitivepredicatecan_destroy()toexpressthatrequirement.ARegulartypecanbeusedtocreateobjects,declarevariables,makecopies,moveobjects,comparevalues,anddefault-construct.Inessence,thenotionofregularityde-nesthebasicsetoperationsandguaranteesthatshouldbeavailableforallvalue-orientedtypes.conceptRegular&#xtype;&#xname;&#x-278;T{requiresMovab&#xT000;le&&Copyab&#xT000;lerequiresconstraintConstructib&#xT000;le//defaultconstruction&&Assignable&#xT,-2;砀T&&//moveassignment&&Assignableconst&#xT,-2;砀T&;//copyassignmentaxiomObject_equality(T&x,T&y){&x==&y&#xT,-2;砀=x==y;//identicalobjectshaveequalvalues}axiomMove_assign_effect(Tx,Ty,T&z){x==y&#xT,-2;砀=(z=move(x))==y&&can_destroy(x);//originalisvalidbutunspecied}axiomCopy_assign_equality(Tx,T&y){(y=x)==x;//acopyisequaltotheoriginal}}TheObject_equalityaxiomrequiresequalityforidenticalobjects(thosehavingthesameaddress).TheMove_assign_effectandCopy_assign_equalityaxiomsex- tendthesemanticsofmoveandcopyconstructiontoassignment.Notethattherequire-mentofassignabilityimpliesthatconst-qualiedtypesarenotRegular.Furthermore,volatile-qualiedtypesarenotregularbecausetheycannotsatisfytheObject_equalityaxiom;thevalueofavolatileobjectmaychangeunexpectedly.Thesedesigndecisionsareintentional.Objectscanbeconst-orvolatile-qualiedtodenoteimmutabilityorvolatility,butthatdoesnotmaketheirvalue'stypeimmutableorvolatile.Also,includ-ingassignmentasarequirementforRegulartypesallowsagreaterdegreeoffreedomforalgorithmimplementers.Notincludingassignabilitywouldmeanthatanalgorithmusingtemporarystorage(e.g.,avariable)wouldberequiredstatetheadditionalrequire-mentaspartofitsinterface,leakingimplementationdetailsthroughtheuserinterface.WenotethatOrderisnotarequirementofRegulartypes.Althoughmanyregulartypesdoadmitanaturalorder,othersdonot(e.g.,comple&#xT000;xandthread),hencethetwoconceptsaredistinct.ThisdenitionissimilartothosefoundinpreviousworkbyDehnertandStepanov[13]andalsobyStepanovandMcJones[34]exceptthatthedesignismademodularinordertoaccommodateabroaderrangeoffundamentalnotions.Inparticular,thesebasicconceptscanbereusedtodeneconceptsexpressingtherequirementsofValueandResourcetypes,bothofwhicharecloselyrelatedtotheRegulartypes,buthaverestrictedsemantics.AValuerepresentspure(immutable)valuesinaprogramsuchastemporariesorconstantexpressions.Valuescanbecopyandmoveconstructed,andcompared,butnotmodied.AResourceisanobjectwithlimitedavailabilitysuchanfstream,oraunique_ptr.Resourcescanbemovedandcompared,butnotcopied.BothValuesandResourcesmayalsobeOrdered.Weomitspecicdenitionsoftheseconceptsbecausetheywerenotexplicitlyrequiredbyanytemplatesinoursurvey;weonlyfoundrequirementsforRegulartypes.ByrequiringessentiallyalltypestobeRegular,wegreatlysimplifyinterfacesandgiveaclearguidelinetoimplementersoftypes.Forexample,atypethatcannotbecopiedisunacceptableforouralgorithmsandsoisatypewithacopyoperatorthatdoesn'tactuallycopy.Otherdesignphilosophiesarepossible;theSTL'snotionoftypeisvalue-oriented;anobjected-orientedsetofconceptswouldprobablynothavethesedenitionsofcopyingandequalityaspartoftheirbasis.5.2TypeAbstractionsThereareasmallnumberoffundamentalabstractionsfoundinvirtuallyallprograms:Boolean,Integral,andRealtypes.Inthissection,wedescribehowwemightdeneconceptsforsuchabstractions.Wesavespecicdenitionsforfuturework,pendingfurtherinvestigationandexperimentation.TheSTLtraditionallyreliesonthebooltyperatherthanamoreabstractnotion,butderivingaBooleanconceptisstraightforward.TheBooleanconceptdescribesageneralizationofthebooltypeanditsoperations,includingtheabilitytoevaluateob-jectsinBooleanevaluationcontexts(e.g.,anifstatement).Moreprecisely,aBooleantypeisaRegular,Orderedtypethatcanbeoperatedonbylogicaloperatorsaswellasconstructedoverandconvertedtoboolvalues.TheBooleanconceptwouldrequireconstraintsforlogicaloperators(e.g.,Logical_and)andbedenedbythesemanticsoftheBoolean_algebraaxiom. OthertypeabstractionscanbefoundintheSTL'snumericlibrary,whichiscom-prisedofonlysixalgorithms.Althoughwedidnotexplicitlyconsiderconceptsinthenumericdomain,wecanspeculateabouttheexistenceanddenitionofsomeconcepts.AprincipleabstractioninthenumericdomainistheconceptofArithmetictypes,thosethatcanbeoperatedonbythearithmeticoperators+,*,-,and/withtheusualsemantics,whichwesuspectshouldbecharacterizedasanIntegralDomain.Assuch,allintegers,realnumbers,rationalnumbers,andcomplexnumbersareArithmetictypes.Strongerdenitionsarepossible;anIntegraltypeisanArithmetictypethatalsosatisesthese-manticalrequirementsofaEuclideanDomain.WenotethatMatricesarenotArithmeticbecauseofnon-commutativemultiplication.Thesemanticsoftheseconceptscanbedenedasaxiomsonthosetypesandtheiroperators.ConceptsdescribingGroups,Rings,andFieldsforthesetypesshouldbeanalogoustothedenitionofBoolean_algebraforBooleantypes.Weleavetheexactspecicationsoftheseconceptsasfutureworkasabroaderinvestigationofnumericalgorithmsandtyperepresentationsisrequired.5.3FunctionAbstractionsFunctionsandfunctionobjects(functors)areonly“almostregular”sowecannotdenethemintermsoftheRegularconcept.Unlikeregulartypes,functionsarenotdefaultconstructibleandfunctionobjectspracticallyneverhaveequalitydened.Manyso-lutionshavebeensuggestedsuchasaconceptSemiregularorimplicitlyaddingthemissingoperationstofunctionsandfunctionobjects.Tocomplicatematters,functionshaveaseconddimensionofregularitydeterminedbyapplicationequality,whichstatesthatafunctionappliedtoequalargumentsyieldsequalresults.Thisdoesnotrequirefunctionstobepure(havingnosideeffects),onlythatanysideeffectsdonotaffectsubsequentevaluationsofthefunctiononequalargu-ments.Athirdpropertyusedintheclassicationoffunctionsandfunctionobjectsisthehomogeneityofargumenttypes.Wecandeneanumberofmathematicalpropertiesforfunctionswhenthetypesoftheirargumentsarethesame.Toresolvethesedesignproblems,wedenetwostaticconstraintsforbuildingfunctionalabstractions:CallableandProcedure.TheCallableconstraintdetermineswhetherornotatypecanbeinvokedasafunctionoverasequenceofargumenttypes.TheProcedureconstraintestablishesthebasictyperequirementsforallproceduralandfunctionalabstractions.constraintProcedureF,typename...Ar&#xtype;&#xname;&#x-278;gs{requiresconstraintConstructibleF,-2;砀const&//hascopyconstruction&&CallableAr,-2;砀gs...;//canbecalledwithArgs...typenameresult_type=result_of(úr1;倀gs...)::type;}Proceduretypesarebothcopyconstructibleandcallableoverasequenceofargu-ments.Thevariadicdenitionofthisconceptallowsustowriteasingleconstraintforfunctionsofanyarity.Theresult_type(thecodomain)isdeducedusingresult_of.Therearenorestrictionsontheargumenttypes,resulttypesorsemanticsofProce-dures;theymay,forexample,modifynon-localstate.Consequently,wecannotspec-ifymeaningfulsemanticsforallprocedures,andsoitisstaticconstraintratherthan aconcept.A(randomnumber)GeneratorisanexampleofaProcedurethattakesnoargumentsand(probably)returnsdifferentvalueseachtimeitisinvoked.AFunctionisaProcedurethatreturnsavalueandguaranteesapplicationequiva-lenceanddeterministicbehavior.Itisdenedas:conceptFunctionF,typename...Ar&#xtype;&#xname;&#x-278;gs:ProcedureAr,-2;砀gs...{requiresconstraint!Samev&#xresu;&#xlt_t;&#xype,;&#x-278;oid;//mustreturnavalueaxiomApplication_equality(Ff,tuple r15;gs...a,tuple r15;gs...b){(a==b) r15;=(f(a...)==f(b...));//equalargumentsyieldequalresults}}TheApplication_equalityaxiomguaranteesthatfunctionscalledonequalargu-mentsyieldequalresults.Thisbehaviorisalsoinvariantovertime,guaranteeingthatthefunctionalwaysreturnsthesamevalueforanyequalarguments.Thesyntaxa...denotestheexpansionofatupleintofunctionarguments.ThehashfunctionparameterofunorderedcontainersisanexampleofaFunctionrequirement.AnOperationisaFunctionwhoseargumenttypesarehomogeneousandwhosedomainisthesameasitscodomain(resulttype):conceptOperationF,Common...Ar&#xtype;&#xname;&#x-278;gs:FunctionAr,-2;砀gs...{requiressizeof...(Args)!=0;//Fmusttakeatleastoneargumenttypenamedomain_type=common_type r15;gs?::type;requiresconstraintConvertible&#xresu;&#xlt_t;&#xype,;&#x-278;domain_type;}Fromthisdenition,anOperationisaFunctionacceptinganon-emptysequenceofargumentsthatshareaCommontype(denedinSect6).Thecommontypeofthefunction'sargumenttypesiscalledthedomain_type.Theresult_type(inheritedindirectlyfromProcedure)mustbeconvertibletothedomain_type.Notethattheconcept'srequirementsarenotapplieddirectlytoFanditsargumenttypes.Instead,theconceptdenesafunctionalabstractionoverFandtheunieddo-maintype.SemanticsforOperationsaremoreeasilydenedwhenthedomainandresulttypeareinteroperable.ThisallowsustousetheOperationconceptasthebasisofalgebraicconcepts,whichwehaveomittedinthisdesign.WenotethatmanyofthefunctionobjectsintheSTL'sfunctionallibrarygenerateOperationmodels(e.g.,less,andlogical_and).ParalleltothethreefunctionalabstractionsProcedure,Function,andOperation,wedenetwopredicateabstractions:PredicateandRelation.APredicateisaFunctionwhoseresulttypecanbeconvertedtobool.PredicatesarerequiredbyanumberofSTLalgorithms;forexample,anyalgorithmendingin_ifrequiresaPredicate(e.g.,nd_-if).Thisspecicationalsomatchesthecommonlyacceptedmathematicaldenitionofapredicateandisafundamentalbuildingblockforotherabstractionsfunctionalabstrac-tions.ARelationisabinaryPredicate.TheaxiomsStrict_weak_orderandStrict_to-tal_orderaresemanticrequirementsontheRelationconcept.Theseconceptsareeasilydened,andtheirsemanticsarewellknown. 5.4IteratorsThedistinctionbetweenconceptandconstrainthasasubstantialimpactonthetradi-tionaliteratorhierarchy[22].WeintroduceanewgeneralIteratorconceptasthebaseoftheiteratorhierarchy.Theinputandoutputaspectsoftheprevioushierarchyarerelegatedtoconstraints.AnIteratorisaRegulartypethatdescribesanabstractionthatcan“move”inasingledirectionusing++(bothpre-andpost-increment)andwhosereferencedvaluecanbeaccessedusingunary*.Theconceptplacesnosemanticrequirementsoneitherthetraversaloperationsorthedereferencingoperation.Inthisway,theIteratorconceptisnotdissimilarfromtheITERATORdesignpattern[17],exceptsyntactically.Aswiththepreviousdesigns,thereareanumberofassociatedtypes.Itsdenitionfollows:conceptIterator&#xRegu;&#xlar-;➀Iter{typenamevalue_type=&#xIter;iterator_traitsalue_type;Movablereference=&#xIter;iterator_traitserence;Signed_intdifference_type=&#xIter;iterator_traitserence_type;typenameiterator_category=&#xIter;iterator_traitsy;Iter&Iter::operator++();//prexincrement:moveforwardDereferenceableIter::operator++(int);//postxincrementreferenceIter::operator*();//dereference}Here,thepre-incrementoperatoralwaysreturnsareferencetoitself(i.e.,ityieldsanIterator).Incontrast,theresultofthepost-incrementoperatoronlyneedstobeDeref-erenceable.Theweaknessofthisrequirementaccommodatesiteratorsthatreturnastate-cachingproxywhenpost-incremented(e.g.,ostream_iterator).TheMovablere-quirementonthereferencetypesimplyestablishesabasisforaccessingtheresult.Thisalsoeffectivelyrequirestheresulttobenon-void.Thedenitionpresentedhereomitsrequirementsforanassociatedpointertypeandfortheavailabilityof&#xIter;-:thearrowoperator.Therequirementsfor&#xIter;-areoddandcon-ditionallydependentupontheiterator'svaluetype[15].Inpreviousdesigns,the&#xIter;-requirementwashandledasanintrinsic;that'smostlikelynecessary.Forward,Bidirectional,andRandomAccessIteratorshavechangedlittleinthisde-sign.TheseconceptsrenethesemanticsoftraversalforIterators.However,InputIter-atorsandOutputIteratorshavebeen“demoted'toconstraints(seebelow).AForwardIteratorisamulti-passIteratorthatabstractsthetraversalpatternsofsingly-linkedlists:conceptForward_iterator&#xtype;&#xname;&#x-278;Iter:&#xIter;Iterator{requiresconstraintConvertibley,forward_iterator_ta&#xiter; tor;&#x_cat;gor;&#x-100;g;requiresconstraint&#xIter;Input_iteratorIterIter::operator++(int);//postxincrement---strengthenIterator'srequirementaxiomMultipass_equality(Iteri,Iterj){(i==j)&#xIter;=(++i==++j);//equaliteratorsareequalaftermoving} axiomCopy_preservation(Iteri){(++Iter{i},*i)==*i;//modifyingacopydoesnotinvalidatetheoriginal}}AnInput_iteratoronlyrequiresitsreferencetypetobeconvertibletoitsvaluetype.ForaForward_iteratorthisrequirementstrengthenedsothat,likethepre-incrementoperator,itspost-incrementmustreturnanIterator.Thetwoaxiomsspecifythese-manticpropertiesofmulti-passiterators:equivalentiteratorswillbeequivalentafterincrementingandincrementingacopyofaniteratordoesnotinvalidatetheoriginal.Finally(andnotably),Forward_iteratorsarestaticallydifferentiatedfromInput_-iteratorsbycheckingconvertibilityoftheiriteratorcategories.Thisallowsthecompilertoautomaticallydistinguishbetweenmodelsofthetwoconceptswithoutrequiringaconceptmap(aswasneededintheC++0xdesign).Consider:templateT,Allocator&#xtype;&#xname;&#x-278;Aclassvector{template&#xIter; tor;&#x-278;Itervector(Iterrst,Iterlast){//generalversion(usesonlyasingletraversal)for(;rst!=last;++rst)push_back(*rst);}templated_iteratororw; r20;Itervector(Iterrst,Iterlast){resize(rst,last);//traverseoncetondsizecopy(rst,last,begin());//traverseagaintocopy}};Thevector'srangeconstructorisoptimizedforForward_Iterators.However,thisisnotjustaperformanceissue.Selectingthewrongversionleadstoserioussemanticproblems.Forexample,invokingthesecond(multi-pass)versionforaninputstreamit-eratorwouldcausethesystemtohang(waitforeverformoreinput).WiththeautomaticconceptcheckingenabledbytheConvertiblerequirement,weleveragetheexistingit-eratorclassicationtoavoidthisproblem.ABidirectionalIteratorisaForwardIteratorthatcanbemovedintwodirections(via++and–).Itabstractsthenotionoftraversalfordoublylinkedlists:concept&#xIter;Bidirectional_iterator:Forwar&#xIter;d_iterator{Iter&Iter::operator--();//prexdecrement:movebackwardsIterIter::operator--(int);//postxdecrementaxiomBidirectional(Iteri,Iterj){i==j&#xIter;=--(++j)==i;}}ARandomAccessIteratorisanOrderedBidirectionalIteratorthatcanbemovedmultiple“jumps”inconstanttime;itgeneralizesthenotionofpointers: conceptRandom_access_iteratordered&#xOr20;Iter:&#xIter;Bidirectional_iterator{Iter&operator+=(Iter,difference_type);Iteroperator+(Iter,difference_type);Iteroperator+(difference_type,Iter);Iter&operator-=(Iter,difference_type);Iteroperator-(Iter,difference_type);difference_typeoperator-(Iter,Iter);//distancereferenceoperator[](difference_typen);//subscriptingaxiomSubscript_equality(Iteri,difference_typen){i[n]==*(i+n);//subscriptingisdenedintermsofpointerarithmetic}axiomDistance_complexity(Iteri,Iterj){runtime_complexity(i-j)==O(1);//theexpressioni-jmustbeconstanttime}}TherequirementsontheresulttypeofthedecrementoperatorsareanalogoustotherequirementsforincrementoperatorsoftheForward_iteratorconcept.TheRandom_-access_iteratorconceptrequiresasetofoperationssupportingrandomaccess(+and-).OfparticularinterestaretherequirementonOrderedandtheabilitytocomputethedistancebetweentwoiterators(inconstanttime)viasubtraction.Semantically,theSub-script_equalityaxiomdenesthemeaningofthesubscriptoperatorintermsofpointerarithmetic.TheDistance_complexityaxiomrequiresthecomputationofdistanceinconstanttime.Similarrequirementsmustalsobestatedforrandomaccessadditionandsubtraction,butareomittedhere.Here,runtime_complexityandOareintrinsicsusedtodescribecomplexityrequirement.Input_iteratorandOutput_iteratoraredenedasconstraintsratherthanconcepts.Toallowproxies,theirconversionandassignmentrequirementsareexpressedintermsofatype“speciedelsewhere.”TheC++0xdesignreliesonassociatedtypes,whichareexpressedasmembertypes.Theseareimplicitparametersthatcannotbeuniversallydeducedfromtheiterator.Asisconventional,werelyontypetraitstosupportthisassociation.Aconstrainedtemplateorotherconceptmustberesponsibleforsupplyingtheexternalargument.However,ourdenitionprovidestheobviousdefaultcase(theiterator'svaluetype):constraintInput_iteratorIter,typenameT=v&#xIter;&#xIter;alue_type{requiresconstraintConvertib&#xIter;leerence,&#xIter;T;}constraintOutput_iteratorIter,typenameT=v&#xIter;&#xIter;alue_type{requiresconstraintAssignab&#xIter;leerence,&#xIter;T;}Here,weassumethatv&#xIter;alue_typeisatemplatealiasyieldingtheappropriatevaluetype.TheconstraintsforInput_iteratorandOutput_iteratorsupporttheabilitytoreadanobjectoftypeTandwriteanobjectoftypeTrespectively. 6ConstraintsInthissection,wegiveanoverviewofconstraintsthathavebeendescribedinprevioussections.ManydiscussedthusfarhavedirectcorollariesintheC++StandardLibrarytypetraitsorareeasilyderived;theyarebasicallyacleaned-upinterfacetowhatisalreadystandard(andnotcountedasconceptsinanydesign).SeveralthatwehaveusedinourimplementationaredescribedinTable2.Table2.Typeconstraints ConstraintDenition Same r15;gs...Denedintermsofis_sameCommon r15;gs..Trueifcommon_type r15;gs...isvalidDerive,&#xT800;Uis_base_of,&#xT800;UConvertible,&#xT800;Uis_convertible,&#xT800;U&#xT000;Signed_intis_signed,&#xT800;U TheSameconstraintrequiresthatallargumenttypesbethesametype.Itisavari-adictemplatethatisdenedrecursivelyintermsofis_same.TheCommonconstraintrequiresitsargumenttypestoallshareacommontypeasdenedbythelanguagere-quirementsoftheconditionaloperator(?:).Findingthecommontypeofasetoftypesimpliesthatalltypesinthatsetcanbeimplicitlyconvertedtothattype.Thisdirectlysupportsthedenitionofsemanticsonthecommontypeofafunction'sargumentsfortheOperationconcept.DerivedandConvertiblearetriviallydenedintermsoftheircorrespondingtypetraits.WenotethatSigned_intisaconstraintbecauseitsdenitionisclosed:onlybuilt-insignedintegraltypessatisfytherequirement(e.g.,int,andlong).Constraintsdescribingthesyntaxofconstruction,destruction,andassignmentaregiveninTable3,andconstraintsdescribingoverloadableoperatorsinTable4.Theconstraintsforconstruction,destruction,andassignmentaretriviallydenedintermsofexistingtypetraits.Theoperatorconstraintsrequiretheexistenceofoverloadableoperatorsforthespeciedtypeparametersandmayspecifyconversionrequirementsontheirresulttypes.Forbinaryoperators,thesecondparameterdefaultstotherstsothat,say,&#xT000;Equalevaluatestheexistenceofoperator==(T,T).Table3.Constraintsforobjectinitialization ConstraintDenition Destructib&#xT000;leis_destructib&#xT000;leConstructible,Ar&#xT800;gs..is_constructible,Ar&#xT800;gs...Assignable,&#xT800;Uis_assignable,&#xT800;U TheEqualandLessconstraintsrequiretheirresultstobebool,whichallowstheconstrainedexpressiontobeevaluatedinaBooleanevaluationcontext.Theotherop-eratorsdonotimposeconstraintsontheirresulttypesbecausewecannotreasonablydeneuniversallyapplicableconversionrequirementsforallusesofthoseoperators.Inessence,theseconstraintsarepurelysyntactic;anymeaningmustbeimposedbysomeotherconceptortemplate. Table4.Constraintsforoverloadableoperators ConstraintDenition Equal,&#xT800;U=Tbooloperator==(T,U)Less,&#xT800;U=Tbooloperator(,U)Logical_and,&#xT800;U=Tautooperator&&(T,U)Logical_or,&#xT800;U=Tautooperator||(T,U)&#xT000;Logical_notautooperator!(T)Deref&#xT000;ernceautooperator*(T) 7ImplementationandValidationWeimplementedthedescribedconceptsandtraitsbybuildingacustomlibraryofconstraintclassesinC++11.Ourapproachblendstraditionaltechniquesforimple-mentingconstraintclasses[31]withtemplatemetaprogrammingfacilities[1].There-sultisalightweightconceptemulationlibrarythatcanbeusedtostaticallyenforceconstraintsontemplateparametersandsupportsconceptoverloadingusingconcept-controlledpolymorphism(enable_if)[23].Thelibraryisimplementedasacorecom-ponentoftheOriginLibraries[38].Tosimplifyexperimentation,thelibrarydoesnotdifferentiatebetweenconceptsandconstraintsexceptthroughnamingconventions.Conceptsnamesintheimplemen-tationarewrittencConcept,constraintnamesarewrittentConstraint(“t”standsfor“typeproperty”)andaxioms,aAxiom.Thisnamingconventionischosenfortheimple-mentationsothatitwillnotcollidewith“real”conceptswhendenedwithlanguagesupport.Forexample,theConstructibleconstraintdescribedin6isimplementedinOriginastConstructible:templateT,typename...Ar&#xtype;&#xname;&#x-278;gsstructtConstructible{tConstructible(){autop=constraints;}staticvoidconstraints(Args...args){T{forward r15;gs(args)...};//usepatternforcopyconstruction}typedeftupleleAr&#xT,-2;砀&#xT,-2;砀gs...requirements;typedeftypename&#xrequ;&#xirem;nts;requires_alltype;staticconstexprboolvalue=type::value;};tConstructibleisaconstraintbecausenosensiblesemanticscanbedenedforconstruction,beyondwhatthelanguagealreadyguaranteesforconstructors.ThetCon-structibleconstructorisresponsibleforinstantiatingtheconstraintsfunction,whichcontainstheusepatternsfortheconcept,whicharesimilartothoseintroducedin[15].Thefunctionparametersoftheconstraintsfunctionintroduceobjects,whichsimpliesthewritingofusepatterns.ThetypeandvaluememberssatisfytherequirementsofatypetraitorBooleanmetafunction.Thesemembers,especiallyvalue,areusedtoreasonaboutthetypeat compiletimewithoutcausingcompilererrors.Thisisusedtoselectbetweenoverloadsbasedonmodeledsatisedrequirementsusingenable_if[23].Allconceptsinthelibraryareautomaticallychecked.Implementingaconceptli-brarythatrequiresuserstowriteexplicitconceptmapswouldrequireustodosoforeverydatastructuretested.ThatapproachisnotneededfortheSTLand,inouropinion,doesnotscalewell.Axiomsarenot(andcannotbe)checkedbythecompilersoforourvalidationwetreatthemascomments.Functiontemplaterequirementsarespeciedbyexplicitconstructionsoftemporaryobjects.Forexample:template&#xtype;&#xname;&#x-278;TTconst&min(Tconst&x,Tconst&y){cOr&#xT000;dered//requiresthatThasoperators&#x,-27;耀,and&#x=,-2;砀=returnyx?y:x;}HerecOr&#xT000;dereddenotesarequirementonthetemplateparameterT.Instanti-atingthealgorithmentailsinstantiatingthecOr&#xT000;deredconstructoranditsnestedrequirements.Compilationterminatesifaconstraintclassisinstantiatedwithtemplateargumentsthatdonotsatisfytherequiredusepatterns.Forclasstemplates,therequirementsarespeciedasbaseclasses.Forexample:template&#xtype;&#xname;&#x-278;TclassVector:private&#xT000;cRegular{/*...*/};Thisensuresthatthecompilerinstantiatestheconceptcheckswhenconstructingobjectsoftheconstrainedclass.Requirementswithinconstraintclassesarewritteninexactlythesameway:explicitconstructionisusedinconjunctionwithusepatterns,andinheritanceisusedtoemulateconceptrenement.TherearenomemoryorperformancecostsinducedbytheuseofOrigin'sconstraintclasses.Constraintinstancesareoptimizedoutofthegeneratedcodeeitherthroughdead-codeeliminationortheemptybaseoptimization.Compiletimescanbeincreasedmarginallybutarenoworsethanusinganyotherconceptcheckinglibrary.WeappliedtheconstraintclassestoasubsetoftheClangandGCCimplementa-tionsoftheStandardLibrary:thefunctional,algorithm,anditeratorcomponents(theSTL).Classandfunctiontemplateconstraintswerewrittenforeachdatastructureandalgorithmexportedbythosecomponents.Weiterativelyrenedboththeconceptsandtheconstraintsasrequiredbythelimitsoftheexperiment.Weusethelibraries'testsuites(justover9,000programsatthetimeofwriting)tocheckthecorrectnessoftheconcepts.AmoresubstantialvalidationofourdesigncouldbeachievedbycompilingalargenumberofC++applicationsagainstthemodiedlibraries,butthetestsuitecoverasufcientnumberofinstantiationssowearecondentinthedesign.Testsuitefailuresgenerallyindicatedoverlystrictconstraintsonatypeoralgo-rithm.Insomecases,suchfailuresalsoindicatedwhatweperceiveasproblemswiththeoriginalconceptualspecicationforthelibrary.Insuchcases,thesefailuresareduetotherepresentationofirregulartypesaslegitimateconcepts.Forexample,strictout-putiteratorssuchasostream_iteratorareIteratorsinprinciplebutareneitherdefaultconstructiblenorequalitycomparable.Wemodiedtheseirregularcasessotheywould modeltherequiredconcepts.ThereareonlyfoursuchiteratorsintheSTL,andtheyareeasilyadaptedtomodelourproposedconcepts.8ConclusionsWestudiedconceptdesignratherthanlanguagedesignforexpressingconceptswiththeaimofbringingempiricalevidencetothecenteroflanguagedesigndiscussions.Wefoundthatexplicitlydifferentiatingbetweenconceptsandconstraintsbasedonse-manticrequirements(axioms)improvedouranalysesandclariedlong-standing“darkcorners”oftheSTLdesign.ItledtospectacularsimplicationandadramaticreductioninthenumberofconceptsneededtodescribetheSTLinterfaces(14ratherthan108).TheSTLinterfaceswerealreadyconsideredwellunderstoodaftermorethanadecade'suseandmuchanalysis,soweconcludethatourconceptdesigntechniqueisnowherenearasobviousasitseemsinretrospect.Ourtechniqueisrootedinclassicalalgebraictheory,sowefurtherconjecturethatitwillbeverywidelyapplicable.Ourconclusionsonlanguagedesignforconceptsare,asweexpectedthemtobe,verytentative.However,wehavedemonstratedacentralroleforaxioms,afeaturethatwaswidelyconjecturedtobeunnecessaryduringtheC++0xdesign.Beyondthat,wefoundconstraintsclassessoexpressiveandmanageableinourimplementationthatwewanttore-examinetheuse-patternapproachforexpressingsyntacticrequirements.WecontinuetoinvestigateconceptsfortheC++StandardLibrarybybroadeningourconceptualanalysistocovernumericandscienticcomputingdomainsandcontainers.WithOrigin,wearepursuingconceptsrelatedtoheapsandgraphs[30].Exploringcon-ceptualdesignsindifferentdomainssupportslanguagedesignbyaddressingabroadersetofusecases.Inparticular,weplantoexamineusesofconceptsinalgorithmspeci-cationswiththeaimofsimplifyingsuchspecications.Conceptsareabstract,general,andmeaningful.Consequently,theyareunlikelytobespecictoaspeciclibrary.Asconceptsmature,theybecomearepositoryoffundamentaldomainknowledge.Thus,weexpectconceptstocrosslibraryboundariestobecomemorewidelyuseful.Weexpectthatourexplorationofthedenitionanduseofconceptswilldecreasethetotalnumberofconcepts(amongalllibraries)whileimprovingtheirqualityandutility.AcknowledgementsThankstoMattAustern,PaulMcJones,GabrielDosReis,andAlexStepanovforcom-mentsthatledtomajorimprovementsandwillbethebasisforfurtherwork.ThisprojectwaspartiallysupportedbyNSFgrantsA3350-32525-CSandA0040-32525-CSandAwardKUS-C1-016-04,madebyKingAbdullahUniversityofScienceandTechnol-ogy(KAUST).References1.Abrahams,D.,Gurtovoy,A.:C++TemplateMetaprogramming:Concepts,Tools,andTech-niquesfromBoostandBeyond.C++In-Depth,AddisonWesley(2004)2.Austern,M.:GenericProgrammingandtheSTL:UsingandExtendingtheC++StandardTemplateLibrary.Addison-WelseyLongman,Boston,Massachusetts,7thedn.(1998) 3.Austern,M.,Stroustrup,B.,Thorup,M.,Wilkinson,J.:UntanglingtheBalancingandSearchingofBalancedBinarySearchTrees.Software:PracticeandExperience33(13),1273–1298(2003)4.Bagge,A.H.,David,V.,Haveraaen,M.:TheAxiomsStrikeBack:TestingwithConceptsandAxiomsinC++.In:8thInternationalConferenceonGenerativeProgrammingandCompo-nentEngineering(GPCE'09).pp.15–24.Denver,Colorado(2010)5.Becker,P.:WorkingDraft,StandardfortheProgrammingLanguageC++.Tech.Rep.N2914,ISO/IECJTC1,InformationTechnologySubcommitteeSC22,ProgrammingLanguageC++(2009)6.Bernardy,J.P.,Jansson,P.,Zalewski,M.,Schupp,S.,Priesnitz,A.:AComparisonofC++ConceptsandHaskellTypeClasses.In:WorkshoponGenericProgramming(WGP'08).pp.37–48.Victoria,Canada(2008)7.Bernardy,J.P.,Jansson,P.,Zalewski,M.,Schupp,S.:GenericProgrammingwithC++Con-ceptsandHaskellTypeClasses–AComparison.JournalofFunctionalProgramming20(3-4),271–302(2010)8.Bracha,G.,Odersky,M.,Stoutamire,D.,Wadler,P.:MakingtheFutureSafeforthePast:AddingGenericitytotheJavaProgrammingLanguage.In:13thACMSIGPLANconferenceonObject-orientedProgramming,Systems,Languages,andApplications(OOPSLA'98).pp.183–200.Vancouver,Canada(1998)9.Davenport,J.H.,Gianni,P.M.,Trager,B.M.:Scratchpad'sViewofAlgebraII:ACategoricalViewofFactorization.In:InternationalSymposiumonSymbolicandAlgebraicComputa-tion(ISSAC'91).pp.32–38.Bonn,Germany(1991)10.Davenport,J.H.,Sutor,R.S.:AXIOM:TheScienticComputationSystem.Springer(1992)11.Davenport,J.H.,Trager,B.M.:Scratchpad'sViewofAlgebraI:BasicCommutativeAlge-bra.In:InternationalSymposiumonDesignandImplementationofSymbolicComputationSystems(DISCO'90).pp.40–54.Capri,Italy(1990)12.David,V.:ConceptsasSyntacticSugar.In:9thInternationalWorkingConferenceonSourceCodeAnalysisandManipulation(SCAM'09).pp.147–156.Alberta,Canada(2009)13.Dehnert,J.,Stepanov,A.:FundamentalsofGenericProgramming.In:InternationalSeminaronGenericProgramming.vol.1766,pp.1–11.Springer,DagstuhlCastle,Germany(1998)14.DosReis,G.:PersonalCommunication(Oct2010)15.DosReis,G.,Stroustrup,B.:SpecifyingC++Concepts.In:33rdSymposiumonPrinciplesofProgrammingLanguages(POPL'06).pp.295–308.Charleston,SouthCarolina(2006)16.DosReis,G.,Stroustrup,B.,Merideth,A.:Axioms:SemanticsAspectsofC++Concepts.Tech.Rep.N2887,ISO/IECJTC1,InformationTechnologySubcommitteeSC22,Program-mingLanguageC++(2009)17.Gamma,E.,Helm,R.,Johnson,R.,Vlissides,J.:DesignPatternsElementsofReusableObject-OrientedSoftware.AddisonWesley(1994)18.Garcia,R.,Järvi,J.,Lumsdaine,A.,Siek,J.,Willcock,J.:AnExtendedComparativeStudyofLanguageSupportforGenericProgramming.JournalofFunctionalProgramming17,145–205(2007)19.Gregor,D.:ConceptGCC(2008),http://www.generic-programming.org/software/ConceptGCC/20.Gregor,D.,Järvi,J.,Siek,J.,Stroustrup,B.,DosReis,G.,Lumsdaine,A.:Concepts:Linguis-ticSupportforGenericProgramminginC++.In:ACMSIGPLANConferenceonObject-OrientedProgramming,Systems,Languages,andApplications(OOPSLA'06).pp.291–310.Portland,Oregon(2006)21.Hewlett-Packard:StandardTemplateLibraryProgrammer'sGuide(1994),http://www.sgi.com/tech/stl/index.html22.InternationalOrganizationforStandards:InternationalStandardISO/IEC14882.Program-mingLanguages—C++(2003)23.Järvi,J.,Willcock,J.,Lumsdaine,A.:Concept-ControlledPolymorphism.In:2ndInterna-tionalConferenceonGenerativeProgrammingandComponentEngineering(GPCE'03).pp.228–244.Erfurt,Germany(2003)24.Jones,M.P.:TypeClasseswithFunctionalDependencies.In:9thEuropeanSymposiumonProgramming(ESOP'00).pp.230–244.Berlin,Germany(2000) 25.Kennedy,A.,Syme,D.:DesignandImplementationofGenericsforthe.NETCommonLan-guageRuntime.In:ACMSIGPLAN2001ConferenceonProgrammingLanguageDesignandImplementation(PLDI'01).pp.1–12.Snowbird,Utah(2001)26.Meyer,B.:Eiffel:TheLanguage.Prentice-Hall(1991)27.Milner,R.,Harper,R.,MacQueen,D.,Tofte,M.:TheDenitionofStandardML-Revised.TheMITPress(1997)28.Musser,D.,Stepanov,A.:Algorithm-orientedGenericLibraries.Software:PracticeandEx-perience24(7),623–642(1994)29.Pirkelbauer,P.,Dechev,D.,Stroustrup,B.:SupportfortheevolutionofC++genericfunc-tions.In:3rdInternationalConferenceonSoftwareLanguageEngineering(SLE'10).pp.123–142.Eindhoven,theNetherlands(2010)30.Siek,J.,Lee,L.Q.,Lumsdaine,A.:TheBoostGraphLibrary:UserGuideandReferenceManual.Addison-Wesley(2001)31.Siek,J.,Lumsdaine,A.:ConceptChecking:BindingParametricPolymorphisminC++.In:1stWorkshoponC++TemplateProgramming.Erfurt,Germany(2000)32.Siek,J.,Lumsdaine,A.:EssentialLanguageSupportforGenericProgramming.In:ACMSIGPLANConferenceonProgrammingLanguageDesignandImplementation(PLDI'05).pp.73–84.Chicago,Illinois(2005)33.Siek,J.,Lumsdaine,A.:LanguageRequirementsforLarge-scaleGenericLibraries.In:4thInternationalConferenceonGenerativeProgrammingandComponentEngineering(GPCE'05).pp.405–421.Tallinn,Estonia(2005)34.Stepanov,A.,McJones,P.:ElementsofProgramming.AddisonWesley,Boston,Mas-sachusetts(2009)35.Stroustrup,B.:ParameterizedTypesforC++.ComputingSystems2(1),55–85(1989)36.Stroustrup,B.:TheDesignandEvolutionofC++.Addison-Wesley(1994)37.Stroustrup,B.:"New"ValueTerminology(2010),http://www2.research.att.com/bs/termi-nology.pdf38.Sutton,A.:OriginC++0xLibraries(2011),http://code.google.com/p/origin39.Sutton,A.,Holeman,R.,Maletic,J.I.:IdenticationofIdiomUsageinC++GenericLi-braries.In:18thInternationalConferenceonProgramComprehension(ICPC'10).pp.160–169.Braga,Portugal(2010)40.Sutton,A.,Maletic,J.I.:AutomaticallyIdentifyingC++0xConceptsinFunctionTemplates.In:24thInternationalConferenceonSoftwareMaintenance(ICSM'04).pp.57–66.Beijing,China(2008)41.Torgersen,M.,Hansen,C.P.,Ernst,E.,vonderAhé,P.,Bracha,G.,Gafter,N.:AddingWild-cardstotheJavaProgrammingLanguage.In:ACMSymposiumonAppliedComputing(SAC'04).pp.1289–1296.Nicosia,Cyprus(2004)42.Veldhuizen,T.:ExpressionTemplates.C++Report7(5),26–31(1995)

Related Contents


Next Show more