/
ThouShaltNotSpecializestdFunctionTemplatesDocumentWG21P0551R0Date2017 ThouShaltNotSpecializestdFunctionTemplatesDocumentWG21P0551R0Date2017

ThouShaltNotSpecializestdFunctionTemplatesDocumentWG21P0551R0Date2017 - PDF document

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

ThouShaltNotSpecializestdFunctionTemplatesDocumentWG21P0551R0Date2017 - PPT Presentation

Contents1Introduction12Discussion121Whatwesaytoday122Whatswrongwiththat223Whatshouldwedo33Analternateapproach34Proposedwording55Acknowledgments66Bibliography67Documenthistory6AbstractThispaperproposes ID: 890951

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

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#:WG21P0551R0Date:2017-02-01Project:JTC1.22.32ProgrammingLanguageC++Audience:LEWG)LWGReplyto:WalterE.Brownwebrown.cpp@gmail.com� Contents1Introduction.............12Discussion..............12.1Whatwesaytoday........12.2What'swrongwiththat?....22.3Whatshouldwedo?.......33Analternateapproach.......34Proposedwording..........55Acknowledgments..........66Bibliography.............67Documenthistory..........6 AbstractThispaperproposestomodifyclause[namespace.std]soas(a)toforbidusersfromspecializingstandardlibraryfunctiontemplatesand(b)toallowfunctionobjectsasimplementationsofstandardlibraryfacilitiesspeciedasfunctiontemplates.Tocreatearchitectureistoputinorder.Putwhatinorder?Functionandobjects.—LECORBUSIER,néCHARLES-ÉDOUARDJEANNERET1IntroductionSpecializingfunctiontemplateshasprovenproblematicinpractice;specializingfunctiontemplatesinnamespacestdhasprovenevenmoreproblematic.Thispaper(a)willciteknowledgableandwell-respectedcolleaguesindescribingthecorelanguagecausesoftheissuesinvolved,and(b)willthenrecommendwordingadjustments(tosubclause[namespace.std])toaddresstheseissuesinthecontextofthestandardlibrary.2Discussion2.1WhatwesaytodayQuotedverbatimfrom[N4618],herearethethreeparagraphsthatconstitutetheentiretyof[namespace.std]: 1ThebehaviorofaC++programisundenedifitaddsdeclarationsordenitionstonamespacestdortoanamespacewithinnamespacestdunlessotherwisespecied.Aprogrammayaddatemplatespecializationforanystandardlibrarytemplatetonamespacestdonlyifthedeclarationdependsonauser-denedtypeandthespecializationmeetsthestandardlibraryrequirementsfortheoriginaltemplateandisnotexplicitlyprohibited. Copyrightc 2017byWalterE.Brown.Allrightsreserved.1 2P0551R0:ThouShaltNotSpecializestdFunctionTemplates! [Footnote:Anylibrarycodethatinstantiatesotherlibrarytemplatesmustbepreparedtoworkadequatelywithanyuser-suppliedspecializationthatmeetstheminimumrequirementsoftheStandard.]2ThebehaviorofaC++programisundenedifitdeclares(2.1)—anexplicitspecializationofanymemberfunctionofastandardlibraryclasstemplate,or(2.2)—anexplicitspecializationofanymemberfunctiontemplateofastandardlibraryclassorclasstemplate,or(2.2)—anexplicitorpartialspecializationofanymemberclasstemplateofastandardlibraryclassorclasstemplate.Aprogrammayexplicitlyinstantiateatemplatedenedinthestandardlibraryonlyifthedeclarationdependsonthenameofauser-denedtypeandtheinstantiationmeetsthestandardlibraryrequirementsfortheoriginaltemplate.3Atranslationunitshallnotdeclarenamespacestdtobeaninlinenamespace(7.3.1).2.2What'swrongwiththat?AccordingtoseveralC++cognoscenti,itisa

2 poorC++programmingpracticetospecializeaf
poorC++programmingpracticetospecializeafunctiontemplate,especiallyoneinnamespacestd.Herearerepresentativeexplanationsandadvice: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:“thisissuehasbeensettledforalongtime....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/. P0551R0:ThouShaltNotSpecializestdFunctionTemplates!3 Whilethisissueh

3 asbeenknownforover15years,itseemsnotpart
asbeenknownforover15years,itseemsnotparticularywellknown.Moreover,thewordingin[namespace.std]isstill,eventoday,beingtweaked,6andtherearepapers(e.g.,[N4381])consideringfurtherrenementsincustomizinglibrary-providedfunctiontemplates.2.3Whatshouldwedo?Weproposeafewrelatedmeasurestoaddressthepresentuncomfortablesituationregardingusercustomizationoffunctiontemplatesinthestandardlibrary.LetFdenoteanarbitrarystandardlibraryfacilitythatisspeciedasanon-memberfunctiontemplate.(ProminentexamplesofsuchanFincludebegin,swap,andforward.)Then:1.ProhibitprogramsfromspecializinganysuchF.(ThisisinadditiontotheexistingprohibitionagainstoverloadinganysuchFinnamespacestd.)2.DespiteF'sspecicationasafunctiontemplate,grantimplementationslicensetoimplementFintheformofaninstantiatedfunctionobjectthathasthespeciedtemplateparameters,functionparameters,andreturntype.Thesechangeswillallowstandardlibraryimplementorstoprovidecustomizationpoints7thatwillsmoothlyinteroperatewithoverloadsprovidedbyusersintheirownnamespaces,thusavoidingsurprisesdueto(common)misunderstandingsofinteractionsofspecializationandoverloading.3AnalternateapproachTheRangesTS[N4620]speciescustomizationpointfunctionalitythatoverlapswhatweproposeabove,butthatalsoappearstogointofargreaterdetailaboutimplementationtechniques.Weareuncertainthatalltheseimplementationdetailsaretrulynecessarytoitsspecicationofcustomizationpoints.Forexample,thefollowingextensivedetails(cross-referenceselided)areprovidedasa“conven-tion”intheTSsubclause“CustomizationPointObjects”[customization.point.object]: 1Acustomizationpointobjectisafunctionobjectwithaliteralclasstypethatinteractswithuser-denedtypeswhileenforcingsemanticrequirementsonthatinteraction.2ThetypeofacustomizationpointobjectshallsatisfySemiregular.3Allinstancesofaspeciccustomizationpointobjecttypeshallbeequal.4ThetypeofacustomizationpointobjectTshallsatisfyInvocable ons;&#xt-60;�T,Args...()whenthetypesofArgs...meettherequirementsspeciedinthatcustomizationpointobject'sdenition.Otherwise,Tshallnothaveafunctioncalloperatorthatparticipatesinoverloadresolution.5Eachcustomizationpointobjecttypeconstrainsitsreturntypetosatisfyaparticularconcept.6Thelibrarydenesseveralnamedcustomizationpointobjects.Ineverytranslationunitwheresuchanameisdened,itshallrefertothesameinstanceofthecustomizationpointobject. 6See,forexample,LWGIssue2139,“Whatisauser-denedtype?”.InC++StandardLibraryActiveIssuesList(RevisionD012),revised2016–12–18at14:12:32UTC(retrieved2016–12–20),http://cplusplus.github.io/LWG/lwg-active.html#2139.7Accordingto[N4381],

4 47;Acustomizationpoint...isafunctionused
47;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/. 4P0551R0:ThouShaltNotSpecializestdFunctionTemplates! 7[Note:Manyofthecustomizationpointobjectsinthelibraryevaluatefunctioncallexpres-sionswithanunqualiednamewhichresultsinacalltoauser-denedfunctionfoundbyargumentdependentnamelookup.Toprecludesuchanexpressionresultinginacalltounconstrainedfunctionswiththesamenameinnamespacestd,customizationpointobjectsspecifythatlookupfortheseexpressionsisperformedinacontextthatincludesdeletedoverloadsmatchingthesignaturesofoverloadsdenedinnamespacestd.Whenthedeletedoverloadsareviable,user-denedoverloadsmustbemorespecializedormoreconstrainedtobeusedbyacustomizationpointobject.—endnote]Inadditiontotheabove“convention,”eachcustomizationpointspecicationcarriessignicantadditionalverbiageregardingitsimplementation.Forexample,hereisthefurtherspecicationofswapfromtheTS'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(),exchangesthede-notedvalues.ranges::swap(E1,E2)isaconstantexpressioniftheconstructorselectedbyoverloadresolutionforT{std::move(E1)}isaconstexprconstructorandtheexpres-sionE1=std::move(E2)canappearinaconstexprfunction.noexcept(ranges::swap(E1,E2))isequalto&#xT000;is_nothrow_move_constructible&&is_no&#xT000;throw_move_assignable.IfeitherMoveConstructibleorAssign

5 ableisnotsatised,theprogramisill-for
ableisnotsatised,theprogramisill-formedwithnodiagnosticrequired.(1.4)—Otherwise,ranges::swap(E1,E2)isill-formed.2Remark:Wheneverranges::swap(E1,E2)isavalidexpression,itexchangesthevaluesdenotedbyE1andE2andhastypevoid.Thereisasimilarlydetailedamountofadditionalspecicationforeachoftheothercus-tomizationpointsintheTS:iter_move,iter_swap,begin,end,cbegin,cend,rbegin,rend,crbegin,crend,size,empty,data,andcdata.Despiteallthisbulk,theTSdoesnotspeaktothefundamentalissueweseektoaddress,namelytoforbidusercodefromprovidinginconsistentreinterpretationsofstandardlibraryfeatures.Itseemsplausiblethatsomehybridofthetwoapproachesmayprovebenecial,butthispaperproposesaminimalistapproachinordertoprovideacontrastingviewpoint. P0551R0:ThouShaltNotSpecializestdFunctionTemplates!5 4Proposedwording8 4.1Adjust[namespace.std]asshown:1 Unless otherwise specied, T thebehaviorofaC++programisundenedifitaddsdeclarationsordenitionstonamespacestdortoanamespacewithinnamespacestd un less oth er wise spec i ed. 2 Unless explicitly prohibited, A aprogrammayaddatemplatespecializationforanystandardlibrary class template or variabletemplatetonamespacestd only if provided that (a)the addeddeclarationdependsonauser-denedtypeand (b)thespecializationmeetsthestandardlibraryrequirementsfortheoriginaltemplate and is not ex plic itly pro hib ited.[Footnote:Anylibrarycodethatinstantiatesotherlibrarytemplatesmustbepreparedtoworkadequatelywithanyuser-suppliedspecializationthatmeetstheminimumrequirementsoftheStandard.] 2 3ThebehaviorofaC++programisundenedifitdeclares( 2 3.1)—anexplicitspecializationofanymemberfunctionofastandardlibraryclasstemplate,or( 2 3.2)—anexplicitspecializationofanymemberfunctiontemplateofastandardlibraryclassorclasstemplate,or( 2 3.2)—anexplicitorpartialspecializationofanymemberclasstemplateofastandardlibraryclassorclasstemplate. 4Aprogrammayexplicitlyinstantiatea classtemplatedenedinthestandardlibraryonlyifthedeclarationdependsonthenameofauser-denedtypeandtheinstantiationmeetsthestandardlibraryrequirementsfortheoriginaltemplate. 5 A program may provide (in a namespace of its own) an overload for any library function template designated as a customizationpoint, provided that (a) the overload's declaration depends on a 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-su

6 pplied overload that meets the minimum r
pplied overload that meets the minimum requirements of the Standard. Therefore an implementation may elect, under the as-if rule ([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 of its operator() must match those of the corresponding customization point's specication.] 3 6Atranslationunitshallnotdeclarenamespacestdtobeaninlinenamespace(7.3.1). 4.2Whereandasshown,designatethefollowingstandardlibraryfunctionalityascustomiza-tionpoints:(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]]. 8Allproposed additionsand dele tionsarerelativetothepost-IssaquahWorkingDraft[N4618].Editorialnotesaredisplayedagainsta graybackground. 6P0551R0:ThouShaltNotSpecializestdFunctionTemplates! [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/WG21doc-umentN4381(pre-Lenexamailing),2015–03–11.http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html.[N4618]RichardSmith:“WorkingDraft,StandardforProgrammingLanguageC++,”ISO/IECJTC1/SC22/WG21documentN4618(post-Issaquahmailing),2016–11–28.http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4618.pdf.[N4620]EricNieblerandCaseyCarter:“WorkingDraft,C++ExtensionsforRanges.”ISO/IECJTC1/SC22/WG21documentN4620(post-Issaquahmailing),2016–11–27.http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/n4620.pdf.7DocumenthistoryVersionDateChanges02017-02-01PublishedasP055

Related Contents


Next Show more