Generic operator overloading for immutable types?
ag0aep6g via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jun 13 12:58:32 PDT 2017
On 06/13/2017 09:29 PM, Gary Willoughby wrote:
> Is it possible for the `result` variable in the following code to be
> returned as an immutable type if it's created by adding two immutable
> types?
Qualify the return type as `inout`:
inout(Rational) opBinary(/*...*/)(/*...*/) inout {/*...*/}
(That second `inout` is the same as the first one in your code.)
Then you get a mutable/const/immutable result when you call the method
on a mutable/const/immutable instance.
It doesn't matter a lot, though. `Rational` is a value type, so you can
convert the return value between qualifiers as you want, anyway. But it
affects what you get with `auto`, of course.
[...]
> struct Rational
> {
> public long numerator;
> public long denominator;
>
> public inout Rational opBinary(string op)(inout(Rational) other) const
`inout` and `const` kinda clash here. Both apply to `this`. But
apparently, the compiler thinks `inout const` is a thing. No idea how it
behaves. I don't think it's a thing in the language. As far as I
understand, you should only put one of const/immutable/inout.
More information about the Digitalmars-d-learn
mailing list