Generic operator overloading for immutable types?
H. S. Teoh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Jun 12 13:10:17 PDT 2017
On Mon, Jun 12, 2017 at 01:08:13PM -0700, Ali Çehreli via Digitalmars-d-learn wrote:
> On 06/12/2017 01:03 PM, Gary Willoughby wrote:
> > On Monday, 12 June 2017 at 19:36:52 UTC, H. S. Teoh wrote:
>
> >> public inout Rational opBinary(string op)(inout Rational rhs)
>
> > Quick question about the signature, if I change it to (note the parens):
> >
> > public inout(Rational) opBinary(string op)(inout(Rational) rhs)
> >
> > It no longer works, why is that?
>
> That's frequently faced issue with D. :) In the first declaration,
> inout applies to the member function.
More precisely, it applies to the `this` reference implicitly passed to
the member function. You need inout to apply to `this`, otherwise
a.opBinary(b) won't work when a is an immutable instance.
> In the second one, it applies only to the return type. Walter has his
> rationale for doing it that way but it's confusing.
[...]
A few years ago we tried lobbying for the language to enforce putting
modifiers that only apply to the function itself on the far right side,
e.g.:
public Rational opBinary(string op)(inout Rational rhs) inout
But it was rejected for various reasons.
Therefore, nowadays I always recommend writing parenthesis with type
modifiers, so that the intent it unambiguous, i.e., always write
`inout(Rational)` rather than `inout Rational`, unless you intend for
`inout` to apply to the function rather than the return value. (And I
apologize for the slip-up in my code example above, where I failed to do
this for the function parameter.)
T
--
Маленькие детки - маленькие бедки.
More information about the Digitalmars-d-learn
mailing list