Tải bản đầy đủ - 0 (trang)
Chapter 64.  Blend static and dynamic polymorphism judiciously

Chapter 64.  Blend static and dynamic polymorphism judiciously

Tải bản đầy đủ - 0trang

Summary

Somuchmorethanameresumofparts:Staticanddynamic

polymorphismarecomplementary.Understandtheirtradeoffs,

useeachforwhatit'sbestat,andmixthemtogetthebestof

bothworlds.



Discussion

Dynamicpolymorphismcomesintheformofclasseswith

virtualfunctionsandinstancesmanipulatedindirectly(through

pointersorreferences).Staticpolymorphisminvolvestemplate

classesandtemplatefunctions.

Polymorphismmeansthatagivenvaluecanhavemorethan

onetype,andagivenfunctioncanacceptargumentsoftypes

otherthantheexacttypesofitsparameters."Polymorphismis

awayofgainingsomeofthefreedomofdynamictypechecking

withoutgivingupthebenefitsofstatictypechecking."

[Webber03]

Thestrengthofpolymorphismisthatthesamepieceofcode

canoperateondifferenttypes,eventypesthatwerenotknown

atthetimethecodewaswritten.Such"post-hocapplicability"

isthecornerstoneofpolymorphismbecauseitamplifiesthe

usefulnessandreusabilityofcode(seeItem37).(Contrastthat

withmonomorphiccodethatrigidlyoperatesonlyonthe

concretetypesitwasmeanttoworkwith.)

Dynamicpolymorphismviapublicinheritanceletsavaluehave

morethanonetype.Forexample,aDerived*pcanbeviewed

asapointernotonlytoaDerived,buttoanobjectofanytype

Basethat'sadirectorindirectbaseofDerived(the

subsumptionproperty).Dynamicpolymorphismisalsoreferred

toasinclusionpolymorphismbecausethesetmodeledbyBase

includesthespecializationsmodeledbyDerived.

Duetoitscharacteristics,dynamicpolymorphisminC++isbest

at:

Uniformmanipulationbasedonsuperset/subset

relationships:Differentclassesthatholdasuperset/subset



(base/derived)relationshipcanbetreateduniformly.A

functionthatworksonEmployeeobjectsworksalsoon

Secretaryobjects.

Statictypechecking:Alltypesarecheckedstaticallyin

C++.

Dynamicbindingandseparatecompilation:Codethatuses

classesinahierarchycanbecompiledapartfromthecode

oftheentirehierarchy.Thisispossiblebecauseofthe

indirectionthatpointersprovide(bothtoobjectsandto

functions).

Binaryinterfacing:Modulescanbelinkedeitherstaticallyor

dynamically,aslongasthelinkedmoduleslayoutthe

virtualtablesthesameway.

Staticpolymorphismviatemplatesalsoletsavaluehavemore

thanonetype.Insideatemplatevoidf(Tt)

{/**/},tcanhaveanytypethatcanbesubstitutedinsidef

torendercompilablecode.Thisiscalledan"implicitinterface,"

incontrasttoabaseclass'sexplicitinterface.Itachievesthe

samegoalofpolymorphismwritingcodethatoperateson

multipletypesbutinaverydifferentway.

Staticpolymorphismisbestat:

Uniformmanipulationbasedonsyntacticandsemantic

interface:Typesthatobeyasyntacticandsemantic

interfacecanbetreateduniformly.Interfacesaresyntactic

andimplicit(notsignature-basedandexplicit),andsoallow

anytypesubstitutionthatfitsagivensyntax.Forexample,

giventhestatementinti=p->f(5):Ifpisapointer

toaBaseclasstype,thiscallsaspecificinterfacefunction,

suchasperhapsavirtualintf(int).Butifpisofa

generictype,thiscallcanbindtoamyriadofthings,



includingthatitmightinvokeanoverloadedoperator->

thatreturnsatypedefiningthefunctionXf(double)

whereXisconvertibletoint.

Statictypechecking:Alltypesarecheckedstatically.

Staticbinding(preventsseparatecompilation):Alltypesare

boundstatically.

Efficiency:Compile-timeevaluationandstaticbindingallow

optimizationsandefficienciesnotavailablewithdynamic

binding.

Decideonyourpriorities,anduseeachtypeofpolymorphism

foritsstrengths.

Prefertoblendbothkindsofpolymorphismtocombinetheir

benefitswhiletryingnottocombinetheirdrawbacks:

Statichelpsdynamic:Usestaticpolymorphismto

implementdynamicallypolymorphicinterfaces.For

example,youmighthaveanabstractbaseclassCommand

anddefinevariousimplementationsastemplate

classConcreteCommand:publicCommand.Examples

includeimplementingtheCommandandVisitordesign

patterns(see[Alexandrescu01]and[Sutter04]).

Dynamichelpsstatic:Offerageneric,comfortable,

staticallyboundinterface,butinternallydispatch

dynamically,soyouofferauniformobjectlayout.Good

examplesarediscriminatedunionimplementations(see

[Alexandrescu02b]and[Boost])andtr1::shared_ptr's

Deleterparameter(see[C++TR104]).

Anyotherblend:Abadblendthatcombinesthe



weaknessesofbothisworsethaneitheralone;agood

blendthatcombinesthebenefitsofbothisbetterthan

eitheralone.Forexample,don'tputvirtualfunctionsintoa

classtemplateunlessyouwantallvirtualfunctionstobe

instantiatedeverytime(thisisinsharpcontrastto

nonvirtualfunctionsoftemplatedtypes).Thecodesizehit

canbeastronomical,andyoumayoverconstrainyour

generictypebyinstantiatingfunctionalitythatisnever

needed.Thestandardfacetsmadethismistake.Don'tmake

itagain.



References

[Alexandrescu01]Đ10[Alexandrescu02b][C++TR104]

[Gamma95][Musser01]Đ1.2-3,Đ17[Stroustrup00]Đ24.4.1

[Sutter00]Đ3[Sutter02]Đ1[Sutter04]Đ17,Đ35

[Vandevoorde03]Đ14[Webber03]Đ8.6



65.Customizeintentionallyandexplicitly

Summary

Discussion

References



Summary

Intentionalisbetterthanaccidental,andexplicitisbetterthan

implicit:Whenwritingatemplate,providepointsof

customizationknowinglyandcorrectly,anddocumentthem

clearly.Whenusingatemplate,knowhowthetemplateintends

foryoutocustomizeitforusewithyourtype,andcustomizeit

appropriately.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 64.  Blend static and dynamic polymorphism judiciously

Tải bản đầy đủ ngay(0 tr)

×