InthisworkweexperimentwithdesignsforconceptsbytryingtominimizethenumberofconceptsrequiredtoconstrainthegenericalgorithmsanddatastructuresofalibraryTodosuchexperimentsweneedwaystorepresentconceptsin ID: 246857
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.
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-braryhasaconceptofanumber,whichhasadefactodenitionintermsofoperationsusedinthelibrarycode.Interpretationsofnumbercanvarydramaticallyfromlibrarytolibrary.Isapolynomialfunctionanumber'?Arenumberssupposedtosupportdivi-sion?Areoperationsonnumberssupposedtobeassociative?Regardless,everygenericMatrixlibraryhasanumberconcept. 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,notalloftheconceptsineitherpublicationareequallyabstract.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).Thedominantphilosophyofconceptdesignhasfocusedonliftingalgorithmsfromspecicimplementationstogenericalgorithmswithspecicrequirementsonarguments[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-poseofconceptsbymakingthemnothingbutarestatementoftherequirementsofaparticularpieceofcode.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.Wechoosethetermconstraintovertraitbecauseofthe variedsemanticsalreadyassociatedthewordtrait.Thewordconstraintalsoem-phasizesthecheckablenatureofthespecications.ThetermsconceptandaxiomarewellestablishedintheC++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,theefforttoclassifydeepenedourunderstandingoftheabstractionandinfourcasesthecanwestateanaxiom?criterionchangedtheclassicationofapredicate,yieldinginretrospectabetterdesign.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]:constraintBalancertype;name;-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_iteratorandool;vectorareirregularinthattheirvaluetypecannotbededucedfromtheirreferencetype.Expressiontemplatesareparagonsofirregularity:theyencodefragmentsofanabstractsyntaxtreeastypesandcansupportlazyevalu-ationwithoutadditionalsyntax[42].Wecan'tsupporteverysuchirregularitywithoutcreatingamessofconceptsthatlackpropersemanticspecicationandarenotstable(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.conceptComparabletype;name;-278;T{requiresconstraintT000;Equal//syntaxofequalityrequiresaxiomEquivT000;alence_relationT000;T;//semanticsofequivalencetemplatePred;icat;-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:conceptOrderedRegu;lar-;➀T{requiresconstraintT000;LessrequiresaxiomStrict_total_orT000;derT000;T;requiresaxiomT000;GreaterrequiresaxiomT000;Less_equalrequiresaxiomT000;Greater_equal}Wefactorouttheaxiomsjusttoshowthatwecan,andbecausetheyareexamplesofaxiomsthatmightndmultipleuses:templatetype;name;-278;TaxiomGreater(Tx,Ty){type;name;-278;(xy)==(y)}templatetype;name;-278;TaxiomLess_equal(Tx,Ty){(x)==!(y)}templatetype;name;-278;TaxiomGreater_equal(Tx,Ty){type;name;-278;(x=y)==!(x)}AswithComparable,thedenitionofrequirementsispredicatedonasyntacticconstraint(Less)andasemanticrequirement(Strict_total_order).Obviously,notalltypesinherentlydeneatotalorder;IEEE754oatingpointvaluesdeneonlyapartialorderwhenconsideringNaNvalues.Becausethisisanaxiomandcan'tbeprovenbyaC++compiler,weareallowedtoassumethatitholds.Therequiredaxiomsconnectthemeaningoftheotherrelationaloperationsto. conceptCopyableleomp; rab;ကT{requiresconstraintDestructibT000;le&&ConstructibleconstT,-2;砀T&axiomCopy_equality(Tx,Ty){x==yT,-2;砀=T{x}==y&&x==y;//copyconstructioncopies(non-destructively)}};ACopyabletypeisbothcopyconstructibleandComparable.TheCopy_equalityaxiomstatesthatacopyofanobjectisequaltoitsoriginal.Copyable(andalsoMov-able)typesmustbeDestructible,ensuringthattheprogramcandestroytheconstructedobjects.conceptMovabletype;name;-278;T{requiresconstraintDestructibT000;le&&ConstructibleT,-2;砀T&&axiomMove_effect(Tx,Ty){x==yT,-2;砀=T{move(x)}==y&&can_destroy(x);//originalisvalidbutunspecied}}AMovabletypeismoveconstructible.Movinganobjectputsthemoved-fromob-jectinavalidbutunspeciedstate.TheC++0xaxiomsyntaxprovidesnowayofex-pressingvalidbutunspeciedsoweintroducetheprimitivepredicatecan_destroy()toexpressthatrequirement.ARegulartypecanbeusedtocreateobjects,declarevariables,makecopies,moveobjects,comparevalues,anddefault-construct.Inessence,thenotionofregularityde-nesthebasicsetoperationsandguaranteesthatshouldbeavailableforallvalue-orientedtypes.conceptRegulartype;name;-278;T{requiresMovabT000;le&&CopyabT000;lerequiresconstraintConstructibT000;le//defaultconstruction&&AssignableT,-2;砀T&&//moveassignment&&AssignableconstT,-2;砀T&;//copyassignmentaxiomObject_equality(T&x,T&y){&x==&yT,-2;砀=x==y;//identicalobjectshaveequalvalues}axiomMove_assign_effect(Tx,Ty,T&z){x==yT,-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.,compleT000;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)areonlyalmostregularsowecannotdenethemintermsoftheRegularconcept.Unlikeregulartypes,functionsarenotdefaultconstructibleandfunctionobjectspracticallyneverhaveequalitydened.Manyso-lutionshavebeensuggestedsuchasaconceptSemiregularorimplicitlyaddingthemissingoperationstofunctionsandfunctionobjects.Tocomplicatematters,functionshaveaseconddimensionofregularitydeterminedbyapplicationequality,whichstatesthatafunctionappliedtoequalargumentsyieldsequalresults.Thisdoesnotrequirefunctionstobepure(havingnosideeffects),onlythatanysideeffectsdonotaffectsubsequentevaluationsofthefunctiononequalargu-ments.Athirdpropertyusedintheclassicationoffunctionsandfunctionobjectsisthehomogeneityofargumenttypes.Wecandeneanumberofmathematicalpropertiesforfunctionswhenthetypesoftheirargumentsarethesame.Toresolvethesedesignproblems,wedenetwostaticconstraintsforbuildingfunctionalabstractions:CallableandProcedure.TheCallableconstraintdetermineswhetherornotatypecanbeinvokedasafunctionoverasequenceofargumenttypes.TheProcedureconstraintestablishesthebasictyperequirementsforallproceduralandfunctionalabstractions.constraintProcedureF,typename...Artype;name;-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...Artype;name;-278;gs:ProcedureAr,-2;砀gs...{requiresconstraint!Samevresu;lt_t;ype,;-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...Artype;name;-278;gs:FunctionAr,-2;砀gs...{requiressizeof...(Args)!=0;//Fmusttakeatleastoneargumenttypenamedomain_type=common_type r15;gs?::type;requiresconstraintConvertibleresu;lt_t;ype,;-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.AnIteratorisaRegulartypethatdescribesanabstractionthatcanmoveinasingledirectionusing++(bothpre-andpost-increment)andwhosereferencedvaluecanbeaccessedusingunary*.Theconceptplacesnosemanticrequirementsoneitherthetraversaloperationsorthedereferencingoperation.Inthisway,theIteratorconceptisnotdissimilarfromtheITERATORdesignpattern[17],exceptsyntactically.Aswiththepreviousdesigns,thereareanumberofassociatedtypes.Itsdenitionfollows:conceptIteratorRegu;lar-;➀Iter{typenamevalue_type=Iter;iterator_traitsalue_type;Movablereference=Iter;iterator_traitserence;Signed_intdifference_type=Iter;iterator_traitserence_type;typenameiterator_category=Iter;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.ThedenitionpresentedhereomitsrequirementsforanassociatedpointertypeandfortheavailabilityofIter;-:thearrowoperator.TherequirementsforIter;-areoddandcon-ditionallydependentupontheiterator'svaluetype[15].Inpreviousdesigns,theIter;-requirementwashandledasanintrinsic;that'smostlikelynecessary.Forward,Bidirectional,andRandomAccessIteratorshavechangedlittleinthisde-sign.TheseconceptsrenethesemanticsoftraversalforIterators.However,InputIter-atorsandOutputIteratorshavebeendemoted'toconstraints(seebelow).AForwardIteratorisamulti-passIteratorthatabstractsthetraversalpatternsofsingly-linkedlists:conceptForward_iteratortype;name;-278;Iter:Iter;Iterator{requiresconstraintConvertibley,forward_iterator_taiter; tor;_cat;gor;-100;g;requiresconstraintIter;Input_iteratorIterIter::operator++(int);//postxincrement---strengthenIterator'srequirementaxiomMultipass_equality(Iteri,Iterj){(i==j)Iter;=(++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,Allocatortype;name;-278;Aclassvector{templateIter; tor;-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:conceptIter;Bidirectional_iterator:ForwarIter;d_iterator{Iter&Iter::operator--();//prexdecrement:movebackwardsIterIter::operator--(int);//postxdecrementaxiomBidirectional(Iteri,Iterj){i==jIter;=--(++j)==i;}}ARandomAccessIteratorisanOrderedBidirectionalIteratorthatcanbemovedmultiplejumpsinconstanttime;itgeneralizesthenotionofpointers: conceptRandom_access_iteratorderedOr20;Iter:Iter;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,theirconversionandassignmentrequirementsareexpressedintermsofatypespeciedelsewhere.TheC++0xdesignreliesonassociatedtypes,whichareexpressedasmembertypes.Theseareimplicitparametersthatcannotbeuniversallydeducedfromtheiterator.Asisconventional,werelyontypetraitstosupportthisassociation.Aconstrainedtemplateorotherconceptmustberesponsibleforsupplyingtheexternalargument.However,ourdenitionprovidestheobviousdefaultcase(theiterator'svaluetype):constraintInput_iteratorIter,typenameT=vIter;Iter;alue_type{requiresconstraintConvertibIter;leerence,Iter;T;}constraintOutput_iteratorIter,typenameT=vIter;Iter;alue_type{requiresconstraintAssignabIter;leerence,Iter;T;}Here,weassumethatvIter;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,T800;Uis_base_of,T800;UConvertible,T800;Uis_convertible,T800;UT000;Signed_intis_signed,T800;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,T000;Equalevaluatestheexistenceofoperator==(T,T).Table3.Constraintsforobjectinitialization ConstraintDenition DestructibT000;leis_destructibT000;leConstructible,ArT800;gs..is_constructible,ArT800;gs...Assignable,T800;Uis_assignable,T800;U TheEqualandLessconstraintsrequiretheirresultstobebool,whichallowstheconstrainedexpressiontobeevaluatedinaBooleanevaluationcontext.Theotherop-eratorsdonotimposeconstraintsontheirresulttypesbecausewecannotreasonablydeneuniversallyapplicableconversionrequirementsforallusesofthoseoperators.Inessence,theseconstraintsarepurelysyntactic;anymeaningmustbeimposedbysomeotherconceptortemplate. Table4.Constraintsforoverloadableoperators ConstraintDenition Equal,T800;U=Tbooloperator==(T,U)Less,T800;U=Tbooloperator(,U)Logical_and,T800;U=Tautooperator&&(T,U)Logical_or,T800;U=Tautooperator||(T,U)T000;Logical_notautooperator!(T)DerefT000;ernceautooperator*(T) 7ImplementationandValidationWeimplementedthedescribedconceptsandtraitsbybuildingacustomlibraryofconstraintclassesinC++11.Ourapproachblendstraditionaltechniquesforimple-mentingconstraintclasses[31]withtemplatemetaprogrammingfacilities[1].There-sultisalightweightconceptemulationlibrarythatcanbeusedtostaticallyenforceconstraintsontemplateparametersandsupportsconceptoverloadingusingconcept-controlledpolymorphism(enable_if)[23].Thelibraryisimplementedasacorecom-ponentoftheOriginLibraries[38].Tosimplifyexperimentation,thelibrarydoesnotdifferentiatebetweenconceptsandconstraintsexceptthroughnamingconventions.Conceptsnamesintheimplemen-tationarewrittencConcept,constraintnamesarewrittentConstraint(tstandsfortypeproperty)andaxioms,aAxiom.Thisnamingconventionischosenfortheimple-mentationsothatitwillnotcollidewithrealconceptswhendenedwithlanguagesupport.Forexample,theConstructibleconstraintdescribedin6isimplementedinOriginastConstructible:templateT,typename...Artype;name;-278;gsstructtConstructible{tConstructible(){autop=constraints;}staticvoidconstraints(Args...args){T{forward r15;gs(args)...};//usepatternforcopyconstruction}typedeftupleleArT,-2;砀T,-2;砀gs...requirements;typedeftypenamerequ;irem;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:templatetype;name;-278;TTconst&min(Tconst&x,Tconst&y){cOrT000;dered//requiresthatThasoperators,-27;耀,and=,-2;砀=returnyx?y:x;}HerecOrT000;dereddenotesarequirementonthetemplateparameterT.Instanti-atingthealgorithmentailsinstantiatingthecOrT000;deredconstructoranditsnestedrequirements.Compilationterminatesifaconstraintclassisinstantiatedwithtemplateargumentsthatdonotsatisfytherequiredusepatterns.Forclasstemplates,therequirementsarespeciedasbaseclasses.Forexample:templatetype;name;-278;TclassVector:privateT000;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-standingdarkcornersoftheSTLdesign.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),12731298(2003)4.Bagge,A.H.,David,V.,Haveraaen,M.:TheAxiomsStrikeBack:TestingwithConceptsandAxiomsinC++.In:8thInternationalConferenceonGenerativeProgrammingandCompo-nentEngineering(GPCE'09).pp.1524.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.3748.Victoria,Canada(2008)7.Bernardy,J.P.,Jansson,P.,Zalewski,M.,Schupp,S.:GenericProgrammingwithC++Con-ceptsandHaskellTypeClassesAComparison.JournalofFunctionalProgramming20(3-4),271302(2010)8.Bracha,G.,Odersky,M.,Stoutamire,D.,Wadler,P.:MakingtheFutureSafeforthePast:AddingGenericitytotheJavaProgrammingLanguage.In:13thACMSIGPLANconferenceonObject-orientedProgramming,Systems,Languages,andApplications(OOPSLA'98).pp.183200.Vancouver,Canada(1998)9.Davenport,J.H.,Gianni,P.M.,Trager,B.M.:Scratchpad'sViewofAlgebraII:ACategoricalViewofFactorization.In:InternationalSymposiumonSymbolicandAlgebraicComputa-tion(ISSAC'91).pp.3238.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.4054.Capri,Italy(1990)12.David,V.:ConceptsasSyntacticSugar.In:9thInternationalWorkingConferenceonSourceCodeAnalysisandManipulation(SCAM'09).pp.147156.Alberta,Canada(2009)13.Dehnert,J.,Stepanov,A.:FundamentalsofGenericProgramming.In:InternationalSeminaronGenericProgramming.vol.1766,pp.111.Springer,DagstuhlCastle,Germany(1998)14.DosReis,G.:PersonalCommunication(Oct2010)15.DosReis,G.,Stroustrup,B.:SpecifyingC++Concepts.In:33rdSymposiumonPrinciplesofProgrammingLanguages(POPL'06).pp.295308.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,145205(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.291310.Portland,Oregon(2006)21.Hewlett-Packard:StandardTemplateLibraryProgrammer'sGuide(1994),http://www.sgi.com/tech/stl/index.html22.InternationalOrganizationforStandards:InternationalStandardISO/IEC14882.Program-mingLanguagesC++(2003)23.Järvi,J.,Willcock,J.,Lumsdaine,A.:Concept-ControlledPolymorphism.In:2ndInterna-tionalConferenceonGenerativeProgrammingandComponentEngineering(GPCE'03).pp.228244.Erfurt,Germany(2003)24.Jones,M.P.:TypeClasseswithFunctionalDependencies.In:9thEuropeanSymposiumonProgramming(ESOP'00).pp.230244.Berlin,Germany(2000) 25.Kennedy,A.,Syme,D.:DesignandImplementationofGenericsforthe.NETCommonLan-guageRuntime.In:ACMSIGPLAN2001ConferenceonProgrammingLanguageDesignandImplementation(PLDI'01).pp.112.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),623642(1994)29.Pirkelbauer,P.,Dechev,D.,Stroustrup,B.:SupportfortheevolutionofC++genericfunc-tions.In:3rdInternationalConferenceonSoftwareLanguageEngineering(SLE'10).pp.123142.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.7384.Chicago,Illinois(2005)33.Siek,J.,Lumsdaine,A.:LanguageRequirementsforLarge-scaleGenericLibraries.In:4thInternationalConferenceonGenerativeProgrammingandComponentEngineering(GPCE'05).pp.405421.Tallinn,Estonia(2005)34.Stepanov,A.,McJones,P.:ElementsofProgramming.AddisonWesley,Boston,Mas-sachusetts(2009)35.Stroustrup,B.:ParameterizedTypesforC++.ComputingSystems2(1),5585(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.160169.Braga,Portugal(2010)40.Sutton,A.,Maletic,J.I.:AutomaticallyIdentifyingC++0xConceptsinFunctionTemplates.In:24thInternationalConferenceonSoftwareMaintenance(ICSM'04).pp.5766.Beijing,China(2008)41.Torgersen,M.,Hansen,C.P.,Ernst,E.,vonderAhé,P.,Bracha,G.,Gafter,N.:AddingWild-cardstotheJavaProgrammingLanguage.In:ACMSymposiumonAppliedComputing(SAC'04).pp.12891296.Nicosia,Cyprus(2004)42.Veldhuizen,T.:ExpressionTemplates.C++Report7(5),2631(1995)