/
ThouShaltNotSpecializestdFunctionTemplatesDocumentWG21P0551R1Date2017 ThouShaltNotSpecializestdFunctionTemplatesDocumentWG21P0551R1Date2017

ThouShaltNotSpecializestdFunctionTemplatesDocumentWG21P0551R1Date2017 - PDF document

josephine
josephine . @josephine
Follow
342 views
Uploaded On 2021-09-30

ThouShaltNotSpecializestdFunctionTemplatesDocumentWG21P0551R1Date2017 - PPT Presentation

Contents1Introduction12Discussion121Whatwesaytoday122Whatswrongwiththat223Whatshouldwedo43Analternateapproach44Proposedwording65Acknowledgments76Bibliography77Documenthistory7AbstractThispaperproposes ID: 890949

148 150 swap 147 150 148 147 swap 151 point http std customization namespace function overload thoushaltnotspecializestdfunctiontemplates ranges x0000

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "ThouShaltNotSpecializestdFunctionTemplat..." 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

1 ThouShaltNotSpecializestdFunctionTemplat
ThouShaltNotSpecializestdFunctionTemplates!Document#:WG21P0551R1Date:2017-10-14Project:JTC1.22.32ProgrammingLanguageC++Audience:LEWG)LWGReplyto:WalterE.Brownwebrown.cpp@gmail.com� Contents1Introduction.............12Discussion..............12.1Whatwesaytoday........12.2What'swrongwiththat?....22.3Whatshouldwedo?.......43Analternateapproach.......44Proposedwording..........65Acknowledgments..........76Bibliography.............77Documenthistory..........7 AbstractThispaperproposestomodifyclause[namespace.std]soas(a)toforbidusersfromspecializingstandardlibraryfunctiontemplatesand(b)toallowfunctionobjectsasimplementationsofstandardlibraryfacilitiesspeciedasfunctiontemplates.Tocreatearchitectureistoputinorder.Putwhatinorder?Functionandobjects.—LECORBUSIER,néCHARLES-ÉDOUARDJEANNERETSpecializationisforinsects.—ROBERTANSONHEINLEIN1IntroductionSpecializingfunctiontemplateshasprovenproblematicinpractice;specializingfunctiontemplatesinnamespacestdhasprovenevenmoreproblematic.Thispaper(a)willciteknowledgableandwell-respectedcolleaguesindescribingthecorelanguagecausesoftheissuesinvolved,and(b)willthenrecommendwordingadjustments(mostlytosubclause[namespace.std])toaddresstheseissuesinthecontextofthestandardlibrary.2Discussion2.1WhatwesaytodayQuotedverbatimfrom[N4687],hereistheentiretyofsubclause[namespace.std]: 1ThebehaviorofaC++programisundenedifitaddsdeclarationsordenitionstonamespacestdortoanamespacewithinnamespacestdunlessotherwisespecied.Aprogrammayaddatemplatespecializationforanystandardlibrarytemplatetonamespacestdonlyifthedeclarationdependsonauser-denedtypeandthespecializationmeetsthestandardlibrary Copyrightc 2017byWalterE.Brown.Allrightsreserved.1 2P0551R1:ThouShaltNotSpecializestdFunctionTemplates! requirementsfortheoriginaltemplateandisnotexplicitlyprohibited.[Footnote:Anylibrarycodethatinstantiatesotherlibrarytemplatesmustbepreparedtoworkadequatelywithanyuser-suppliedspecializationthatmeetstheminimumrequirementsofthisInternationalStandard.]2ThebehaviorofaC++programisundenedifitdeclaresanexplicitorpartialspecializationofanystandardlibraryvariabletemplate,exceptwhereexplicitlypermittedbythespecicationofthatvariabletemplate.3ThebehaviorofaC++programisundenedifitdeclares(3.1)—anexplicitspecializationofanymemberfunctionofastandardlibraryclasstemplate,or(3.2)—anexplicitspecializationofanymemberfunctiontemplateofastandardlibraryclassorclasstemplate,or(3.3)—anexplicitorpartialspecializationofanymemberclasstemplateofastandardlibraryclassorclasstemplate,or(3.4)—adeductionguideforanystandardlibraryclasstemplate.Aprogrammayexplicitlyinstantiateatemplatedenedinthestandardlibraryonlyifthedeclarationdependsonthenameofauser-denedtypeandtheinstantiationmeetsthestandardlibraryrequirementsfortheoriginaltempl

2 ate.4Atranslationunitshallnotdeclarename
ate.4Atranslationunitshallnotdeclarenamespacestdtobeaninlinenamespace(10.3.1).(Notethatparagraph2andbullet3.4arerelativelyrecentadditionstothisspecication.)2.2What'swrongwiththat?Let'sstartwithasimpleexampleinwhichthenamegisobviouslyoverloaded: 1templateT las;&#xs-60;�voidg(Tconst&);//functiontemplate 2�templatevoidg&#xint0;(int);//explicitspecialization 3voidg(double);//functionGiventhesedeclarationsandconsideringsuchcallsasg(42),g(4.2),g('4'),org("4.2"),what'sthemaximumsizeofthesetofcandidatefunctionsthatwouldbeconsideredduringoverloadresolution?ManyC++programmersseemsurprisedbytheanswer.STOP!Pleasehaveananswerinmindbeforereadingfurther. P0551R1:ThouShaltNotSpecializestdFunctionTemplates!3 SPOILERALERT!,Answer:Theoverloadsetdescribedabovewouldconsistofatmostonlytwocandidates:thefunctiong(double)(declaredinline3above),and&#xT000;g(const&),acompiler-synthesizedfunctiontemplatespecializationoftheprimarytemplate(line1above),withthetypeTdeducedfromthetypeofthecall'sargument.Mostprogrammersseemtounderstandthattheordinaryfunction(line3)shouldparticipateinoverloadresolution.However,experiencesuggeststhatmanyC++programmersexpectthesetofcandidatesforoverloadresolutiontoincludetheprimarytemplate(line1),theexplicitspecialization(line2),orboth.Reline1:Giventhatthecompileristryingtondafunctiontocall,noprimarytemplatecanbeacandidate:overloadresolutionconsidersonlyfunctiondeclarations,andaprimarytemplateis,afterall,notafunction.However,afunctioncanbecompiler-synthesizedfromaprimaryfunctiontemplate—ultimately,that'sthepurposeofdeclaringatemplate.Reline2:Explicitspecializationsarenevercandidatestoparticipateinoverloadresolution.However,ifoverloadresolutionselectsthesynthesizedspecializationasthebettermatch,thenpartialorderingwilldeterminewhetheritis(a)theexplicittemplatespecializationor(b)thesynthesizedtemplatespecializationthatistobe(instantiated,ifneeded,andthen)called.AsproclaimedbyseveralC++cognoscenti,itisforthesereasonsapoorC++programmingpracticetospecializeafunctiontemplate,especiallysoinnamespacestd.Herearerepresentativesummaryexplanationsandadvice:HerbSutter:“specializationsdon'tparticipateinoverloading....Ifyouwanttocustomizeafunctionbasetemplateandwantthatcustomizationtoparticipateinoverloadresolution(or,toalwaysbeusedinthecaseofexactmatch),makeitaplainoldfunction,notaspecialization.And,ifyoudoprovideoverloads,avoidalsoprovidingspecializations.”1DavidAbrahams:“it'swrongtousefunctiontemplatespecialization[because]itinteractsinbadwayswithoverloads....Forexample,ifyouspecializetheregularstd::swapfor&#xmyty;&#xpe00;std::vector,yourspecializationwon'tgetchosenoverthestandard'svector-specicswap,becausespecializationsaren'tconsideredduringoverloadresolution.”2HowardHinnant:“thisissuehasbeensett

3 ledforalongtime....DisregardDave'sexpert
ledforalongtime....DisregardDave'sexpertopinion/answerinthisareaatyourownperil.”3EricNiebler:“[becauseof]thedecidedlywonkywayC++resolvesfunctioncallsintem-plates...,[w]emakeanunqualiedcalltoswapinordertondanoverloadthatmightbedenedin...associatednamespaces...,andwedousingstd::swapsothat,ontheoff-chancethatthereisnosuchoverload,wendthedefaultversiondenedinthestdnamespace.”4HighIntegrityC++CodingStandard:“Overloadresolutiondoesnottakeintoaccountexplicitspecializationsoffunctiontemplates.Onlyafteroverloadresolutionhaschosenafunctiontemplatewillanyexplicitspecializationsbeconsidered.”5 1HerbSutter:“WhyNotSpecializeFunctionTemplates?”http://www.gotw.ca/publications/mill17.htm,2009(re-trieved2016–10–17).OriginallypublishedinC/C++UsersJournal,19(7),July2001.2DavidAbrahams:Replyto“Howtooverloadstd::swap().”http://stackoverow.com/questions/11562/how-to-overload-stdswap#comment-5729583,2011–02–24(retrieved2016–10–17).3HowardHinnant:Replyto“Howtooverloadstd::swap().”http://stackoverow.com/questions/11562/how-to-overload-stdswap#8439357,2011–12–08(retrieved2016–10–17).4EricNiebler:“CustomizationPointDesigninC++11andBeyond.”http://ericniebler.com/2014/10/21/customization-point-design-in-c11-and-beyond,2014–10–21(retrieved2016–10–17).5ProgrammingResearchLtd.:“Donotexplicitlyspecializeafunctiontemplatethatisoverloadedwithothertemplates,”InHighIntegrityC++CodingStandard,version4.0,2013–10–03(retrieved2016–10–20).http://www.codingstandard.com/rule/14-2-2-do-not-explicitly-specialize-a-function-template-that-is-overloaded-with-other-templates/. 4P0551R1:ThouShaltNotSpecializestdFunctionTemplates! Whilethisissuehasbeenknownforover15years,itseemsnotparticularywellknownamongthegeneralpopulationofC++programmers.Moreover,thewordingin[namespace.std]isstill,eventoday,beingtweaked,6andtherearepapers(e.g.,[N4381])consideringfurtherrenementsincustomizinglibrary-providedfunctiontemplates.2.3Whatshouldwedo?Weproposemeasurestoaddressthepresentuncomfortablesituationregardingusercustomizationoffunctiontemplatesinthestandardlibrary.Inthefollowingsummaryofourproposal,letFdenoteanarbitrarystandardlibraryfacilitythatisspeciedasanon-memberfunctiontemplate.(ProminentexamplesofsuchanFincludebegin,swap,andforward.)1.First,let'sprohibitprogramsfromspecializinganysuchF.(Thisisinadditiontothelong-standingprohibitionagainstoverloadinganysuchFinnamespacestd.)2.Then,despiteF'sspecicationasafunctiontemplate,let'spermitimplementationstocodeFintheformofaninstantiatedfunctionobjectthathasthespeciedtemplateparameters,functionparameters,andreturntype.Together,theseadjustmentswillnotonlyreduceprogrammer

4 uncertaintyregardingcustomizationofstand
uncertaintyregardingcustomizationofstandardlibraryfacilities(“shouldIspecializeorshouldIoverload?”),theywillalsoallowstandardlibraryimplementorstoprovidecustomizationpoints7thatwillsmoothlyinteroperatewithoverloadsprovidedbyusersintheirownnamespaces,thusavoidingsurprisesdueto(common)misunderstandingsofinteractionsofspecializationandoverloading.Finally,wenotethat[P0684R0]hasalreadyproposed“rulesforwell-behavedusercode.”Amongtheserules(whichwerediscussedandgenerallyendorsedduringWG21'srecentTorontomeeting),wendthefollowingtobeofspecialrelevancewithrespecttothepresentproposal: Donotdenenamesinnamespacestd...,exceptasspecicallydirectedforlibraryextensionpoints.Donotforwarddeclaresymbolsfromnamespacestd.Donottaketheaddressoffunctionsormemberfunctionsinnamespacestd.Moregenerally,donotdependonthesignatureofstandardAPIs—assumeonlythatitiscallableasspecied.DonotdependonthepresenceorabsenceofAPIs....Webelievethatthepresentproposalisentirelyconsistentwiththisrecommendedapproach.3AnalternateapproachTheRangesTS[N4684]speciescustomizationpointfunctionalitythatoverlapswhatweproposeabove,butthatalsoappearstogointofargreaterdetailaboutimplementationtechniques.Weareuncertainthatalltheseimplementationdetailsaretrulynecessarytoitsspecicationofcustomizationpoints.Forexample,thefollowingextensivedetails(cross-referenceselided)areprovidedasa“conven-tion”intheTSsubclause“CustomizationPointObjects”[customization.point.object]: 6See,forexample,LWGIssue2139,“Whatisauser-denedtype?”InC++StandardLibraryActiveIssuesList(RevisionD012),revised2016–12–18at14:12:32UTC(retrieved2016–12–20),http://wg21.link/lwg2139.7Accordingto[N4381],“Acustomizationpoint...isafunctionusedbytheStandardLibrarythatcanbeoverloadedonuser-denedtypesintheuser'snamespaceandthatisfoundbyargument-dependentlookup.”Lessformally,EricNieblerdenescustomizationpointsas“hooksusedbygenericcodethatend-userscanspecializetocustomizethebehaviorfortheirtypes.”See“CustomizationPointDesigninC++11andBeyond.”2014–10–21(retrieved2017–01–26).http://ericniebler.com/2014/10/21/customization-point-design-in-c11-and-beyond/. P0551R1:ThouShaltNotSpecializestdFunctionTemplates!5 1Acustomizationpointobjectisafunctionobjectwithaliteralclasstypethatinteractswithuser-denedtypeswhileenforcingsemanticrequirementsonthatinteraction.2ThetypeofacustomizationpointobjectshallsatisfySemiregular.3Allinstancesofaspeciccustomizationpointobjecttypeshallbeequal.4ThetypeofacustomizationpointobjectTshallsatisfyInvocable ons;&#xt-60;�T,Args...()whenthetypesofArgs...meettherequirementsspeciedinthatcustomizationpointobject'sdenition.Otherwise,Tshallnothaveafunctioncallo

5 peratorthatparticipatesinoverloadresolut
peratorthatparticipatesinoverloadresolution.5Eachcustomizationpointobjecttypeconstrainsitsreturntypetosatisfyaparticularconcept.6Thelibrarydenesseveralnamedcustomizationpointobjects.Ineverytranslationunitwheresuchanameisdened,itshallrefertothesameinstanceofthecustomizationpointobject.7[Note:Manyofthecustomizationpointobjectsinthelibraryevaluatefunctioncallexpres-sionswithanunqualiednamewhichresultsinacalltoauser-denedfunctionfoundbyargumentdependentnamelookup.Toprecludesuchanexpressionresultinginacalltounconstrainedfunctionswiththesamenameinnamespacestd,customizationpointobjectsspecifythatlookupfortheseexpressionsisperformedinacontextthatincludesdeletedoverloadsmatchingthesignaturesofoverloadsdenedinnamespacestd.Whenthedeletedoverloadsareviable,user-denedoverloadsmustbemorespecializedormoreconstrainedtobeusedbyacustomizationpointobject.—endnote]Inadditiontotheabove“convention,”eachcustomizationpointspecicationcarriessignicantadditionalverbiageregardingitsimplementation.Forexample,hereisthefurtherspecication(cross-referencesagainelided)ofswapfromtheTS's[utility.swap]: 1Thenameswapdenotesacustomizationpointobject.Theeffectoftheexpressionranges::swap(E1,E2)forsomeexpressionsE1andE2isequivalentto:(1.1)—(void)swap(E1,E2),ifthatexpressionisvalid,withoverloadresolutionperformedinacontextthatincludesthedeclarations templateT las;&#xs-60;�voidswap(T&,T&)=delete; templateT,size_tN las;&#xs-60;�voidswap(T(&)[N],T(&)[N])=delete;anddoesnotincludeadeclarationofranges::swap.IfthefunctionselectedbyoverloadresolutiondoesnotexchangethevaluesdenotedbyE1andE2,theprogramisill-formedwithnodiagnosticrequired.(1.2)—Otherwise,(void)swap_ranges(E1,E2)ifE1andE2arelvaluesofarraytypesofequalextentandranges::swap(*(E1),*(E2))isavalidexpression,exceptthatnoexcept(ranges::swap(E1,E2))isequaltonoexcept(ranges::swap(*(E1),*(E2))).(1.3)—Otherwise,ifE1andE2arelvaluesofthesametypeTwhichmeetsthesyntacticre-quirementsof&#xT000;MoveConstructible()and&#xT&,T;Assignable(),exchangesthedenotedvalues.ranges::swap(E1,E2)isaconstantexpressioniftheconstructorselectedbyoverloadresolutionforT{std::move(E1)}isaconstexprconstructorandtheexpressionE1=std::move(E2)canappearinaconstexprfunction.noexcept(ranges::swap(E1,E2))isequalto&#xT000;is_nothrow_move_constructible&&&#xT000;is_nothrow_move_assignableT::value.IfeitherMoveConstructibleorAssignableisnotsatised,theprogramisill-formedwithnodiagnosticrequired.(1.4)—Otherwise,ranges::swap(E1,E2)isill-formed. 6P0551R1:ThouShaltNotSpecializestdFunctionTemplates! 2Remark:Wheneverranges::swap(E1,E2)isavalidexpression,itexchangesthevaluesdenotedbyE1andE2andhastypevoid.Thereisasimilarlydetailedamountofadditionalspecicationforeachoftheothercus-tomizationpointsintheTS:iter_move,iter

6 _swap,begin,end,cbegin,cend,rbegin,rend,
_swap,begin,end,cbegin,cend,rbegin,rend,crbegin,crend,size,empty,data,andcdata.Despiteallthisbulk,theTSdoesnotspeaktothefundamentalissueweseektoaddress,namelytoforbidusercodefromprovidinginconsistentreinterpretationsofstandardlibraryfeatures.Itseemsplausiblethatsomehybridofthetwoapproachesmayprovebenecial,butthispaperproposesaminimalistapproachinordertoprovideacontrastingviewpoint.4Proposedwording8 4.1Adjust[namespace.std]asshown:1 The Unless otherwise specied, thebehaviorofaC++programisundenedifitaddsdeclarationsordenitionstonamespacestdortoanamespacewithinnamespacestd un less oth er wise spec i - ed. 2 A Unless explicitly prohibited, aprogrammayaddatemplatespecializationforanystandardlibrary classtemplatetonamespacestd only if provided that (a)the addeddeclarationdependson a at least oneuser-denedtypeand (b)thespecializationmeetsthestandardlibraryrequirementsfortheoriginaltemplate and is not ex plic itly pro hib ited.[Footnote:Anylibrarycodethatinstantiatesotherlibrarytemplatesmustbepreparedtoworkadequatelywithanyuser-suppliedspecializationthatmeetstheminimumrequirementsoftheStandard.] 2 3ThebehaviorofaC++programisundenedifitdeclaresanexplicitorpartialspecializationofanystandardlibraryvariabletemplate,exceptwhereexplicitlypermittedbythespecicationofthatvariabletemplate. 3 4ThebehaviorofaC++programisundenedifitdeclares( 3 4.1)—anexplicitspecializationofanymemberfunctionofastandardlibraryclasstemplate,or( 3 4.2)—anexplicitspecializationofanymemberfunctiontemplateofastandardlibraryclassorclasstemplate,or( 3 4.3)—anexplicitorpartialspecializationofanymemberclasstemplateofastandardlibraryclassorclasstemplate,or( 3 4.4)—adeductionguideforanystandardlibraryclasstemplate. 5Aprogrammayexplicitlyinstantiatea classtemplatedenedinthestandardlibraryonlyifthedeclaration (a)dependsonthenameof a at least oneuser-denedtypeand (b)theinstantiationmeetsthestandardlibraryrequirementsfortheoriginaltemplate. 6 In its own namespace, a program may provide an overload for any library function template designated as a customizationpoint, provided that (a) the overload's declaration depends on at least one user-dened type and (b) the overload meets the standard library requirements for the customization point. [Note: this permits a (qualied or unqualied) call to the customization point to invoke the most appropriate overload for the given arguments.] [Footnote: Any library customization point must be prepared to work adequately with any user-dened overload that meets the minimum requirements of the Standard. Therefore an implementation may elect, under the as-if rule 8Allproposed additionsand dele tionsarerelativetothepost-TorontoWorkingDraft[N4687].Editorialnotesaredisplayedagainsta graybackground. P0551R1:Thou

7 ShaltNotSpecializestdFunctionTemplates!7
ShaltNotSpecializestdFunctionTemplates!7 ([intro.execution]), to provide any customization point in the form of an instantiated function object ([function.objects]) even though the customization point's specication is in the form of a function template. The template parameters of each such function object and the function parameters and return type of the object's operator() must match those of the corresponding customization point's specication.] 4 7Atranslationunitshallnotdeclarenamespacestdtobeaninlinenamespace(10.3.1). 4.2Whereandasshown,designatethefollowingstandardlibrarycomponentsascustomizationpoints:(a)swap;(b)therangeaccessalgorithmsbegin,end,andtheirvariants;and(c)thecontaineraccessalgorithmssize,empty,anddata. [utility.swap]1Remarks:Thisfunction is a designated customization point ([namespace.std]] andshallnotparticipateinoverloadresolutionunless.... [iterator.range]1Inadditiontobeingavailableviainclusionofthe&#xiter; tor;header,thefunctiontemplatesin24.7areavailablewhenanyofthefollowingheadersareincluded: rra;&#xy000;,Þqu;,orw; rd_;&#xlist;,...,and&#xvect;&#xor00;. Each of these templates is a designated cus tom- i za tion point ([namespace.std]]. [iterator.container]1Inadditiontobeingavailableviainclusionofthe&#xiter; tor;header,thefunctiontemplatesin24.8areavailablewhenanyofthefollowingheadersareincluded: rra;&#xy000;,Þqu;,orw; rd_;&#xlist;,...,and&#xvect;&#xor00;. Each of these templates is a designated cus tom- i za tion point ([namespace.std]].5AcknowledgmentsManythanks,fortheirthoughtfulcomments,toAndreySemashevandtheotherreadersofprepublicationdraftsofthispaper.6Bibliography[N4381]EricNiebler:“SuggestedDesignforCustomizationPoints.”ISO/IECJTC1/SC22/WG21docu-mentN4381(pre-Lenexamailing),2015–03–11.http://wg21.link/n4381.[N4684]EricNieblerandCaseyCarter:“WorkingDraft,C++ExtensionsforRanges.”ISO/IECJTC1/SC22/WG21documentN4684(post-Torontomailing),2017–07–31.http://wg21.link/n4684.[N4687]RichardSmith:“WorkingDraft,StandardforProgrammingLanguageC++.”ISO/IECJTC1/SC22/WG21documentN4687(post-Torontomailing),2017–07–30.http://wg21.link/n4687.[P0684R0]TitusWinters,BjarneStroustrup,etal.:“C++Stability,Velocity,andDeploymentPlans.”ISO/IECJTC1/SC22/WG21documentP0684R0(pre-Torontomailing),2017–06–19.http://wg21.link/p0684r0.7DocumenthistoryRev.DateChanges02017-02-01PublishedasP0551R0,pre-Kona.12017-10-14Updatedcontentandbibliographytoreectthepost-TorontoWorkingDraftsandotherrecentdevelopments.Added(§2.2)examplewithextendedexplanations.Remarked(§2.3)onconsistencywith[P0684R0].Adjustedcitationstousehttp://wg21.link.Madenumerousminoreditorialandformattingimprovements.PublishedasP0551R1,pre-Albuqu

Related Contents


Next Show more