Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unary minus overload: member or non-member?

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?

like image 842
Cubbi Avatar asked Sep 09 '11 15:09

Cubbi


People also ask

How do you overload unary minus operator?

Overload unary minus operator in C++?The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it.

Is unary minus left or right associative?

Because unary operators are right associative the expression *p++ will be evaluated as *(p++) .

Is unary operator is overloaded using member function then it takes?

When unary operators are overloaded through a member function, they do not take any explicit arguments. But when overloaded by a friend function, they take one argument. When binary operators are overloaded through a member function they take one explicit argument.


1 Answers

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).

like image 189
Mark B Avatar answered Oct 18 '22 14:10

Mark B