Generic collection/element function signatures in D2 versus D1

Steven Schveighoffer schveiguy at yahoo.com
Tue Sep 7 11:06:58 PDT 2010


On Tue, 07 Sep 2010 11:37:20 -0400, Pelle <pelle.mansson at gmail.com> wrote:

> On 09/07/2010 04:33 PM, Steven Schveighoffer wrote:
>> Yes, a valid return. Your function should be:
>>
>> void foo(void delegate(const(C) f) const
>>
>> It helps to understand that inout/const/immutable has NOTHING to do with
>> code generation, it only has to do with limiting what compiles. For this
>> reason, an inout function is compiled once, and works on all three
>> constancies (4 if you have a nested inout function). For the entire
>> function any inout variable is treated as a non-changeable value, just
>> like const. Then when you return, it's converted at the call site back
>> to the constancy with which it was called. If the return value is void,
>> then there's nothing to convert, and no reason to use inout over const.
>>
>> I'll repeat -- there is no benefit to inout if you are not returning
>> anything.
>>
>> -Steve
>
> That's not an equivalent function signature. Or maybe it is, but look at  
> this (sorry it's so long):
>
> class C {
>      int x;
>      this(int y) { x = y; }
>
>      inout(int*) foo() inout {
>          return &x;
>      }
>      void bar(void delegate(int*) f) {
>          f(&x);
>      }
>      void bar(void delegate(const(int*)) f) const {
>          f(&x);
>      }
>      void bar(void delegate(immutable(int*)) f) immutable {
>          f(&x);
>      }
> }
>
> void main() {
>
>      immutable(int)* wah;
>      void wahwah(immutable(int*) x) {
>          wah = x;
>      }
>      auto c = new immutable(C)(10);
>      wahwah(c.foo);  // why is this privilegied with inout
>      c.bar(&wahwah); // and this not?
>
>      writeln(*wah);
>
> }
>
> Can't use void delegate(const(int*)) there.

Thanks for clarifying, I didn't quite understand the usage before.

This is a limitation of inout's design.  Technically inout requires a  
single inout output, and can have multiple inout inputs.  Your example  
matches that description, so in theory it's possible.

But to simplify things, a function's only inout output must be on the  
return value.  So things like void fn(inout int* x, out inout(int) y)  
don't qualify either.

IMO there is a whole host of implicit delegate casting that should be  
possible, but isn't, including delegate contravariance.  However, let's  
get inout working as it's currently designed before we go relaxing the  
requirements.  I'm not a compiler/language designer, so I'm unsure if what  
you want has any pitfalls.

-Steve


More information about the Digitalmars-d-learn mailing list