C++.Coding.Standards.1918.Rules.Guidelines [Electronic resources]

Herb Sutter, Andrei Alexandrescu

نسخه متنی -صفحه : 521/ 146
نمايش فراداده

Discussion

Although anyone would agree (we hope) that one should not implement subtraction in an

operator+ implementation, other cases can be subtle. For example, does your

Tensor class's

operator* mean the scalar product or the vector product? Does

operator+=( Tensor& t, unsigned u ) add

u to each of

t 's elements, or will it resize

t ? In such ambiguous or counterintuitive cases, prefer using named functions instead of fostering cryptic code.Item 32): "When in doubt, do as the

int s do." [Meyers96] Mimicking the behavior of and relationships among operators on built-in types ensures that you don't surprise anyone. If your semantics of choice are likely to raise eyebrows, maybe operator overloading is not a good idea.

Programmers expect operators to come in bundles. If the expression

a @

b is well formed for some operator

@ you define (possibly after conversions), ask: Can the caller also write

b @ a without surprises? Can the caller write

a @= b ? (See Item 27.) If the operator has an inverse (e.g.,

+ and

- , or

* and

/ ), are both supported?

Named functions are less likely to have such assumed relationships, and therefore should be preferred for clearer code if there can be any doubt about semantics.