[ref variables] Allow `auto ref`
Quirin Schroll
qs.il.paperinik at gmail.com
Tue Jul 30 22:03:48 UTC 2024
On Tuesday, 30 July 2024 at 05:43:24 UTC, IchorDev wrote:
> On Monday, 29 July 2024 at 15:26:39 UTC, Quirin Schroll wrote:
>> In particular in generic code, `auto ref` variables that infer
>> `ref` if and only if the initializer is an lvalue could be
>> quite valuable. The same is true for `foreach` over ranges,
>> where the foreach variable would infer `ref` if `front` is an
>> lvalue (be it a variable or a function that returns by
>> reference) and lastly, for conditions, `if (auto ref x = f())`
>> could infer `ref` from the value category of the initializer,
>> like any other variable.
>
> This makes a lot of sense. I’d also love it if `auto ref`
> worked inside all templates, not just template functions. Often
> I want to do this:
> ```d
> struct S(T){
> this(auto ref T x){}
> }
> ```
> But I’d get an error:
> ```d
> S!long x; //Error: cannot explicitly instantiate template
> function with `auto ref` parameter
> ```
> If I make `this` a template function it works. For template
> functions, even explicit instantiation works just fine. This
> requirement feels rather silly and leads to a lot of
> unnecessary parameter-less templates.
By virtue of how `auto ref` works (and is expected to work), this
doesn't make sense. It determines if the parameter is `ref` from
the argument passed to the function at IFTI. You can't have IFTI
if your function isn't a template.
I can only guess what you actually want and it might be what I
proposed in one of the *DIP Ideas* forum, which I called
`@universal ref`. It does not infer anything from the argument,
but binds lvalues normally by reference and materializes rvalues
at the caller side and passes them by reference as well.
More information about the Digitalmars-d
mailing list