Tải bản đầy đủ - 0 (trang)
Chapter 26.  Preserve natural semantics for overloaded operators

Chapter 26.  Preserve natural semantics for overloaded operators

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

Summary

Programmershatesurprises:Overloadoperatorsonlyforgood

reason,andpreservenaturalsemantics;ifthat'sdifficult,you

mightbemisusingoperatoroverloading.



Discussion

Althoughanyonewouldagree(wehope)thatoneshouldnot

implementsubtractioninanoperator+implementation,other

casescanbesubtle.Forexample,doesyourTensorclass's

operator*meanthescalarproductorthevectorproduct?Does

operator+=(Tensor&t,unsignedu)addutoeachoft's

elements,orwillitresizet?Insuchambiguousor

counterintuitivecases,preferusingnamedfunctionsinsteadof

fosteringcrypticcode.

Forvaluetypes(butnotalltypes;seeItem32):"Whenin

doubt,doastheintsdo."[Meyers96]Mimickingthebehavior

ofandrelationshipsamongoperatorsonbuilt-intypesensures

thatyoudon'tsurpriseanyone.Ifyoursemanticsofchoiceare

likelytoraiseeyebrows,maybeoperatoroverloadingisnota

goodidea.

Programmersexpectoperatorstocomeinbundles.Ifthe

expressiona@biswellformedforsomeoperator@youdefine

(possiblyafterconversions),ask:Canthecalleralsowriteb@

awithoutsurprises?Canthecallerwritea@=b?(SeeItem

27.)Iftheoperatorhasaninverse(e.g.,+and-,or*and/),

arebothsupported?

Namedfunctionsarelesslikelytohavesuchassumed

relationships,andthereforeshouldbepreferredforclearercode

iftherecanbeanydoubtaboutsemantics.



Exceptions

Therearehighlyspecializedlibraries(e.g.,parsergenerators

andregularexpressionengines)thatdefinedomain-specific

conventionsforoperatorsthatareverydifferentfromtheirC++

meanings(e.g.,aregularexpressionenginemightuse

operator*toexpress"zeroormore").Preferinsteadtofindan

alternativetounusualoperatoroverloading(e.g.,[C++TR104]

regularexpressionsusestrings,sothat*canbeusednaturally

withoutoverloadingoperators).Ifaftercarefulthoughtyou

choosetouseoperatorsanyway,makesureyoudefinea

coherentframeworkforyourconventionsandthatyoudon't

steponthetoesofanybuilt-inoperator.



References

[Cline99]Đ23.02-06[C++TR104]Đ7[Dewhurst03]Đ85-86

[Koenig97]Đ4[Lakos96]Đ9.1.1[Meyers96]Đ6

[Stroustrup00]Đ11.1[Sutter00]Đ41



None27.Preferthecanonicalformsof

arithmeticandassignmentoperators

Summary

Discussion

Examples

Exceptions

References



Summary

Ifyoua+b,alsoa+=b:Whendefiningbinaryarithmetic

operators,providetheirassignmentversionsaswell,andwrite

tominimizeduplicationandmaximizeefficiency.



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

Chapter 26.  Preserve natural semantics for overloaded operators

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

×