Generic operator overloading for immutable types?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 13 13:50:49 PDT 2017


On 6/13/17 3:58 PM, ag0aep6g wrote:
> 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.

Yes exactly. I prefer personally to have value types always return 
mutable. You can always declare the result to be immutable or const, but 
declaring mutable is not as easy. e.g.:

immutable ReallyLongValueTypeName foo1();
ReallyLongValueTypeName foo2();

version(bad)
{
    auto x = foo1;
    ReallyLongValueTypeName y = foo1;
}
version(good)
{
    immutable x = foo2;
    auto y = foo2;
}

>
> [...]
>> 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.

const(inout) actually *is* a thing :)

It's a type constructor that can be implicitly cast from immutable. This 
has advantages in some cases.

See (horribly written) table at the bottom if the inout function section 
here: http://dlang.org/spec/function.html#inout-functions

Also I talked about it last year at Dconf 2016: 
http://dconf.org/2016/talks/schveighoffer.html

However, I find it very surprising that inout and const can combine the 
way you have written it. Even though it does make logical sense. I'd 
suspect it would be a good candidate for a "you didn't really mean that" 
error from the compiler, but it might be hard to decipher from the 
parsed code.

-Steve


More information about the Digitalmars-d-learn mailing list