Is there any alternative to function pointers in c++?

文章推薦指數: 80 %
投票人數:10人

I don't think there is any widely accepted advice to avoid function pointers however there are some alternatives. Resultsfromthe2022DeveloperSurveyarenowavailable SoftwareEngineeringStackExchangeisaquestionandanswersiteforprofessionals,academics,andstudentsworkingwithinthesystemsdevelopmentlifecycle.Itonlytakesaminutetosignup. Signuptojointhiscommunity Anybodycanaskaquestion Anybodycananswer Thebestanswersarevotedupandrisetothetop Home Public Questions Tags Users Companies Unanswered Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Isthereanyalternativetofunctionpointersinc++? AskQuestion Asked 8years,8monthsago Modified 8years,8monthsago Viewed 9ktimes 5 5 Iamanovicec++programmerwhokeptanideathatfunctionpointersareathingofCandOOPinC++doesnotrecommenditsusage. IknowwhatIwritehereisvague/broad.Butitwillbegreatifsomebodycouldcommentwhethermyideaiscompletelywrongorsomethingsensible. Thanks. c++object-orientedc Share Improvethisquestion Follow askedOct7,2013at11:50 NeonGlowNeonGlow 17711silverbadge55bronzebadges 7 1 Itsnotreallyclearwhatyou'retryingtoachievewithfunctionpointers? – MattD Oct7,2013at11:51 Iamaskingitgenerally.Sorryforbeingvaguehere.JustlikeC++recommendusageofconstinsteadof#define,inasimilarwayisthereanyrecommendationnottousefunctionpointers. – NeonGlow Oct7,2013at11:53 2 Notreally.There'snothinginherentlybadaboutfunctionpointers.There'salwaysbadusageofthemhowever;)(otherthanthecachemissyou'llprobablygetwithyourinstructioncache) – MattD Oct7,2013at12:00 3 @NeonGlowThereisnorulesayingyoushouldn'tusethem,butthereareprobablywaysofstructuringyourcodeinsuchawaythatyoudon'tneedthem.Italldependsontheproblemyou'retryingtosolve. – James Oct7,2013at12:16 2 Whataboutstd::function(intheheader)? – hlt Oct7,2013at16:53  |  Show2morecomments 3Answers 3 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 17 Idon'tthinkthereisanywidelyacceptedadvicetoavoidfunctionpointershowevertherearesomealternatives. Virtualmethods OneofthemostcommonusesoffunctionpointersinCistoimplementdynamicdispatch.InC++howeverthiscanbedoneforyou(forsingledispatch)byusingvirtualfunctions,indeedtheusualimplementationisthatthecompilercreatesessentiallyatableoffunctionpointers. Functors intheC++sense,afunctorisasmallutilityclassthatoverloadsoperator()tobehavelikeafirstclassfunction,asit'sanormalclassyoucanpassitsobjectsaroundlikeanyotherobjectswithoutneedforfunctionpointers. Lambdas essentiallyprovideamoreconvenientwaytodeclarefunctorsinline. Templates Provideagenericwaytouse/consumefunctionpointers,functorsorlambdas.Soyoucanwritehigherorderfunctionswithoutneedingfunctionpointers,eitherbyusingastd::functionparameterordirectlyusingatemplateparameter. Share Improvethisanswer Follow editedOct7,2013at21:58 answeredOct7,2013at12:23 jk.jk. 10.1k11goldbadge3232silverbadges4343bronzebadges 4 3 Mightbeusefultomentionstd::bindandstd::function.Thefirstcreatesfunctorsandthesecondisagenericfunctorholder. – MSalters Oct7,2013at16:19 addedstd::function,notaddedbindasI'mnotsureitreallyanswersthequestion,whileitdoescreateanewfunctoritsmoreaboutpartiallyapplyingafunctor,no? – jk. Oct7,2013at22:00 2 Also:pointerstonon-staticmemberfunctions. – Kaz Oct7,2013at22:25 1 @jk.:bindwillpartiallyapplyfunctors,yes,butalsomanyothercallablethings.Includingthosepointerstonon-staticmemberfunctions,whichneedanobject. – MSalters Oct7,2013at23:00 Addacomment  |  3 Hereisoneexamplewhereuseofmemberfunctionpointer-withinaclass,asanimplementationdetail-isperfectlyacceptable,ifoneworkswithperformance-sensitivecodefordifferentCPUarchitectures. SeetheC++FAQsfortheproperuseofmemberfunctionpointer.Itrequiresadifferentsyntaxthanstaticfunctionpointers. (ThanksforKazforthesuggestion.) classSomePerformanceCriticalOperation { private: //thetypedeclarationofamemberfunctionpointer typedefint(SomePerformanceCriticalOperation::*ProcessPtr)(size_tbytesToProcess,void*dataPtr); //theinstanceofamemberfunctionpointer,tobeassignedtoamemberfunction //(insidetheconstructor) ProcessPtrm_ptr; public: SomePerformanceCriticalOperation() { cpu_featuresfeat=::GetCpuFeatures(); if(TestBit(feat,cpu_features_SSE41)) m_ptr=&SomePerformanceCriticalOperation::Process_SSE41; elseif(TestBit(feat,cpu_features_SSSE3)) m_ptr=&SomePerformanceCriticalOperation::Process_SSSE3; elseif(TestBit(feat,cpu_features_SSE3)) m_ptr=&SomePerformanceCriticalOperation::Process_SSE3; elseif(TestBit(feat,cpu_features_SSE2)) m_ptr=&SomePerformanceCriticalOperation::Process_SSE2; elseif(TestBit(feat,cpu_features_MMX)) m_ptr=&SomePerformanceCriticalOperation::Process_MMX; else m_ptr=&SomePerformanceCriticalOperation::Process_CPlusPlus; } //TheCPU-specificfunctions,asusual.(Omitted.) intProcess_SSE41(size_tbytesToProcess,void*dataPtr){...} }; Share Improvethisanswer Follow editedApr12,2017at7:31 CommunityBot 1 answeredOct8,2013at4:14 rwongrwong 16.5k33goldbadges3232silverbadges7878bronzebadges Addacomment  |  1 CertainlyCprogrammersusedtousefunctionpointersalot,butmostofthoseuseshavebeensurpassedwithOOalternatives-thoughtheymightnotbeobviouswithoutexaminingtheproblembeingsolvedratherthanthesolutionitself.Forexample,theywerepopularinimplementingstatemachinesbutaC++programmerwouldprefertouseafactorypattern. Oneconcepttheyarestillnecessaryforisimplementingadelegate(possiblytheonlyreasontouseoneinthe21stcentury!?).Providedaspartofthelanguageinotherplacesthepoorc++developerstillhastowritehisown-butit'sfuntodo(no!?)andyoucanfindadescriptionofhowtodoithere:StackOverflow Share Improvethisanswer Follow editedMay23,2017at12:40 CommunityBot 1 answeredOct21,2013at11:25 GrimmTheOpinerGrimmTheOpiner 28411silverbadge55bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoSoftwareEngineeringStackExchange!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedc++object-orientedcoraskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool Upcomingcleanupofduplicatevotes ShouldtherebeashortersubdomainfortheSoftwareEngineeringStackExchange? Related 5 Isitacceptablepracticetogiveanobjectapointerto“theworld”? 2 Functionlocals:variableusedinjustonefunction 34 Howtohavetwodifferentprogramswithtwodifferentlanguagesinteract? 10 Concretetypes-asdescribedbyStroustrup-C++ProgrammingLanguage4thed 2 What'stherightOOwaytocreateacounter/inventoryclassthatworksforbothdifferentiatedandundifferentiatedcountables? 8 "Immutable"interfaces 4 Whatisthepurposeofwritingfunctionsandmethods?Whenshouldyoumakeasnippetofcodeintoafunctionormethod? 1 Canencapsulation/informationhidingcauseproblemsinerroridentifying/locating? 7 HowtoapplyOOPtorealworldexampleswithoutputtingalllogicinManagerclasses? HotNetworkQuestions Isthereanysign"theWest"isdeliberatelytryingtoprolongfightinginUkraineforthesakeoffighting? /var/loghasreached56.6GB.Howtocleanitandmakemorespace? ArrayaccessisO(1)impliesafixedindexsize,whichimpliesO(1)arraytraversal? Iboughtmyfirstroadbike,andithurtsmybackandhands Changeinterfacedependingonifstatement Generatetabulardatadynamicallyincluding`\hline` SeparationoftheChurchandStateinHinduism Whydoesthegovernmentnotintroduceanamendmenttotheconstitutiontoallowabortion? TheUnaverageables \scaleboxincolumnspecificationoperator>{...} Checkamushroomforest WhydidoldconsoleshavespecialRAMdedicatedforaspecifictask? HP2000FTSBportedtoMSP430FR5994 Couldsomeonepleaseexplainthewordorderhere? Lookingforthenameforanabstractclassthatmodelsfunctionsasobjects HowshallIproceedifmycarmaycontainillegaldrugsanddrugparaphernaliabeforeenteringCanadabycarfromtheUS? JustificationforaMagicschoolbeingdangerous WhatarethemainargumentsusedbyChristianpro-liferstojustifytheirstanceagainstabortion? Whatdoes"CATsthreeandfour"mean? Ican'tfindtheGeoreferencer Whydoprogunandantiabortion(andviceversa)viewsgotogetherintheUSA? Whatisthis"padding"onscrews? Ambiguousdeathvsperfectscanner DoSteenrodSquareshavenaturalitywithhomomorphismsthatdon'tcomefromcontinousmaps morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. default Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?