Tải bản đầy đủ - 0 (trang)
Chapter 57.  Keep a type and its nonmember function interface in the same namespace

Chapter 57.  Keep a type and its nonmember function interface in the same namespace

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

Summary

Nonmembersarefunctionstoo:Nonmemberfunctionsthatare

designedtobepartoftheinterfaceofaclassX(notably

operatorsandhelperfunctions)mustbedefinedinthesame

namespaceastheXinordertobecalledcorrectly.



Discussion

Bothpublicmemberfunctionsandnonmemberfunctionsform

partofthepublicinterfaceofaclass.TheInterfacePrinciple

states:ForaclassX,allfunctions(includingnonmember

functions)thatboth"mention"Xandare"suppliedwith"Xin

thesamenamespacearelogicallypartofX,becausetheyform

partofX'sinterface.(SeeItem44and[Sutter00].)

TheC++languageisexplicitlydesignedtoenforcetheInterface

Principle.Thereasonwhyargument-dependentlookup(ADL,

alsoknownasKoeniglookup)wasaddedtothelanguagewas

toensurethatcodethatusesanobjectxoftypeXcanuseits

nonmemberfunctioninterface(e.g.,cout<
thenonmemberoperator<
memberfunctions(e.g.,x.f(),whichrequiresnospecial

lookupbecausefisclearlytobelookedupinthescopeofX).

ADLensuresthatnonmemberfunctionsthattakeXobjectsand

thataresuppliedwithX'sdefinitioncanparticipateasfirst-class

membersofX'sinterface,justlikeX'sdirectmemberfunctions

naturallydo.

Inparticular,theprimarymotivatingexampleforADLwasthe

casewhereXisstd::string(see[Sutter00]).

ConsideraclassX,definedinnamespaceN:

classX{

public:

voidf();

};

Xoperator+(constX&,constX&);



Callerswilltypicallywanttowritecodelikethis,wherex1,x2,

andx3areobjectsoftypeX:

x3=x1+x2;



Iftheoperator+isdeclaredinthesamenamespaceasX,

there'snoproblem,andsuchcodealwaysjustworks,because

thesuppliedoperator+willbelookedupusingADL.

Iftheoperator+isnotdeclaredinthesamenamespaceasX,

thecaller'scodefailstowork.Thecallerhastwoworkarounds

tomakeitwork.Thefirstistouseexplicitqualification:

x3=N::operator+(x1,x2);



Thisisdeplorableandshamefulbecauseitrequirestheuserto

giveupnaturaloperatorsyntax,whichisthepointofoperator

overloadinginthefirstplace.Theonlyotheroptionistowritea

usingstatement:

usingN::operator+;

//or:usingnamespaceN;

x3=x1+x2;



Writingeitheroftheindicatedusingstatementsisperfectly

acceptable(seeItem59),butthecallerdoesn'thavetojump

throughthesehoopswhentheauthorofXdoestherightthing

andputsoperator+forXobjectsintothesamenamespaceas

X.

Fortheflipsideofthisissue,seeItem58).



Examples

Example1:Operators.Thestreamingoperator<
operator>>forobjectsofsomeclasstypeXareperhapsthe

mostcompellingexamplesoffunctionsthatareclearlypartof

theinterfaceoftheclassX,butwhicharealwaysnonmember

functions(thisisofnecessity,becausetheleft-handargument

isastream,notanX).Thesameargumentappliestoother

nonmemberoperatorsonXobjects.Makesurethatyour

operatorsappearinthesamenamespaceastheclassonwhich

theyoperate.Whenyouhavetheoption,prefermaking

operatorsandallotherfunctionsnonmembernonfriends(see

Item44).

Example2:Otherfunctions.IftheauthorofXsuppliesnamed

helperfunctionsthattakeXobjects,theyshouldbesuppliedin

thesamenamespace,otherwisecallingcodethatusesXobjects

willnotbeabletousethenamedfunctionswithoutexplicit

qualificationorausingstatement.



References

[Stroustrup00]Đ8.2,Đ10.3.2,Đ11.2.4[Sutter00]Đ31-34



58.Keeptypesandfunctionsinseparate

namespacesunlessthey'respecifically

intendedtoworktogether

Summary

Discussion

References



Summary

Helppreventnamelookupaccidents:Isolatetypesfrom

unintentionalargument-dependentlookup(ADL,alsoknownas

Koeniglookup),andencourageintentionalADL,byputtingthem

intheirownnamespaces(alongwiththeirdirectlyrelated

nonmemberfunctions;seeItem57).Avoidputtingatypeinto

thesamenamespaceasatemplatedfunctionoroperator.



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

Chapter 57.  Keep a type and its nonmember function interface in the same namespace

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

×