Why D const is annoying

Steven Schveighoffer schveiguy at yahoo.com
Mon Dec 12 10:25:07 PST 2011


On Mon, 12 Dec 2011 12:49:11 -0500, Timon Gehr <timon.gehr at gmx.ch> wrote:

> On 12/12/2011 05:46 PM, Steven Schveighoffer wrote:

>> I still am uneasy with
>> allowing applying a wildcard to a reference underneath to mutable
>> references. I know it doesn't work for const.
>
> There is nothing being applied, inout is just matched. After the  
> matching, inout vanishes (it is replaced by nothing, const or immutable)  
> and if that _inout-free_ parameter list still typechecks with the  
> arguments, then it can be invoked. It is simply a case of parametric  
> polymorphism.
>
> void good(ref inout(int)* a, ref inout(int)* b);
>
> is simultaneously these three functions: (duplicating the code that way  
> is the poor man's inout)
>
> void good(ref int* a, ref int* b){ a = b; }
> void good(ref immutable(int)* a, ref immutable(int)* b){ a = b; }
> void good(ref const(int)* a, ref const(int)* b){ a = b; }
>
> None of these applies any type modifier at any level.
>
> It suffices if any of those three typechecks for the call to the  
> polymorphic one to succeed safely. (because the body of 'good' treats  
> its arguments like const).

This is a great way to think about inout in general:

1. all inout parmeters are matched against int, immutable, and inout.  If  
all of them match that qualifier, then that qualifier is substituted for  
inout.
2. If 1. does not match any of those, const substituted for inout.
3. Normal function call rules apply.  That is, just because a match is  
found doesn't mean the function can be called (as you have demonstrated).
4. Anything that is inout inside a function is treated the same as it is  
now (similarly to immutable, except for const(inout(...)) ).

I always thought of inout as being something performed by the compiler,  
while calling the function.  But it's almost just a way to repaint the  
parameters/return type of an existing function before applying normal  
function call rules.

I'm cautiously optimistic about this.  I want to see what Kenji thinks, at  
this point he probably understands inout better than me.  I think actually  
his first patch did not require inout on the return type, and I insisted  
it was required, that might have been a mistake to do that (removing this  
requirement indirectly fixes 6809 as well).

-Steve


More information about the Digitalmars-d mailing list