Syntax ideas for `ref` returning delegate and FP parameters

Q. Schroll qs.il.paperinik at gmail.com
Sun Apr 11 20:40:20 UTC 2021


On Sunday, 11 April 2021 at 05:44:58 UTC, user1234 wrote:
> On Saturday, 10 April 2021 at 14:27:31 UTC, Q. Schroll wrote:
>> Currently in D, one cannot directly express that a function 
>> parameter's type is a delegate or function pointer that 
>> returns by `ref`. If you write
>> ```D
>> void f(ref int delegate() dg) { .. }
>> ```
>> then `dg` will be bound by reference which is probably not 
>> what the user likely intended. It is equivalent to:
>> ```D
>> alias DG = int delegate();
>> void f(ref DG dg) { .. }
>> ```
>
> Slightly off topic but very curiously `auto ref` seems to have 
> for effect to set the function pointer type return as `ref` 
> rather than the parameter itself
>
> ```d
> void f(DG/* = int function()*/)(auto ref DG dg) {
>     dg()++;
> }
>
> ref int a() {
>     static int b;
>     return b;
> }
>
> void main() {
>     f(&a);
>     assert(a == 1); // passes
> }
> ```
>
> a bug certainly.

No. When doing `f(&a)`, the `auto ref` boils down to by copy 
(i.e. no `ref`) and `DG` is inferred by IFTI to be `int 
function() ref` which can easily be observed using `pragma(msg, 
DG)` in `f`. You can remove `auto ref` no problem. If you replace 
the comment by `: int function()`, you get a compile error, 
because `ref` return and value return are incompatible.


More information about the Digitalmars-d mailing list