6

Given that prefix unary operators can be "implemented by a non-static member function with no parameters or a non-member function with one parameter" (§13.5.1[over.unary]/1), is there a difference besides the usual encapsulation/code reuse design rationales that apply to any member/non-member function choices?

For binary operators, there's a semantic difference because non-members allow implicit conversions of their left-hand operands. There doesn't seem to be anything like that for the unary operators, yet the standard defines std::complex's unary negation operator as a non-member (§26.4.6[complex.ops]), while std::valarray's and std::duration's unary negation operators are members (§26.6.2.6[valarray.unary], §20.11.5.3[time.duration.arithmetic]). Is there a nuance?

Community
  • 1
  • 1
Cubbi
  • 46,567
  • 13
  • 103
  • 169
  • 1
    When citing specific sections of the standard, you might want to mention which version you're referring to. – André Caron Sep 09 '11 at 15:16
  • @André Caron Cited from the n3290 version of C++11, which is why I was able to bring up `duration`. – Cubbi Sep 09 '11 at 15:29

2 Answers2

2

As far as I'm aware there are no differences as compared to deciding if a non-operator function should be member or non-member. Obviously prefer non-member, non-friend when possible (like the standard algorithms).

Mark B
  • 95,107
  • 10
  • 109
  • 188
0

Using members when possible makes more sense, since you don't have to go crazy with friends. But otherwise, it is just a code style decision.

Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
  • 1
    What about the Sutter/Alexandrescu new age guideline about making everything nonmember nonfriend if possible? – Cubbi Sep 09 '11 at 15:27
  • @Cubbi Yes it is always best to give the least possible access rights, but I prefer my code succinct. – Šimon Tóth Sep 09 '11 at 15:33