Unary minus overload: member or non-member?

Given that the prefix unary operators can be "implemented by a non-static member function without parameters or a non-member function with one parameter" (ยง13.5.1 [over.unary] / 1), is there a difference besides the usual justification for the reuse design of encapsulation / code that apply to any election of members / non-members?

There is a semantic difference for binary operators, since non-members allow implicit conversions of their left operands. It seems that there is nothing like this for unary operators, but the standard defines the std::complex unary negation operator as non-member (ยง26.4.6 [complex.ops]), and std::valarray and std::duration Unary negation operators are members ( ยง26.6.2.6 [valarray.unary], ยง20.11.5.3 [time.duration.arithmetic]). Is there a nuance?

+6
source share
2 answers

As far as I know, there is no difference compared to deciding whether a non-operator function should be a member or not a member. Obviously, they prefer a non-member, not a friend, when possible (for example, standard algorithms).

+2
source

Using members whenever possible makes more sense since you don't need to go crazy with friends. But the rest is just a code style solution.

0
source

Source: https://habr.com/ru/post/896996/


All Articles