Finding out ref-ness of the return of an auto ref function

Paul Backus snarwin at gmail.com
Fri Jun 12 16:15:10 UTC 2020


On Friday, 12 June 2020 at 14:56:41 UTC, Arafel wrote:
> Hi all,
>
> I'm hitting a problem that it's making crazy... is there any 
> way to find out if the return of an `auto ref` function is 
> actually ref or not?
>
> So, according to the documentation [1] it depends on the return 
> expressions... however in my case I'm implementing `opDispatch` 
> in a wrapper type (and trying to carry over the ref-ness), so I 
> don't know how can I check it.
>
> Now, the whole point of this wrapper is to act differently 
> based on whether the return is a reference or not (it already 
> checks for `hasIndirections`, which btw doesn't help here 
> either).
>
> I've tried to use `__traits(isRef, ??? ) but I haven't been 
> able to find out how to use it, it seems to be meant for 
> parameters. Perhaps it would make sense to have something like 
> `traits(isRef, return)`?
>
> Also I have tried making two different overloads, with and 
> without ref, but it didn't work either...
>
> A.
>
>
> [1]: https://dlang.org/spec/function.html#auto-ref-functions

I think I have something that works:

ref int foo();
int bar();

enum isLvalue(string expr) = q{
     __traits(compiles, (auto ref x) {
         static assert(__traits(isRef, x));
     }(} ~ expr ~ q{))
};

pragma(msg, mixin(isLvalue!"foo()")); // true
pragma(msg, mixin(isLvalue!"bar()")); // false

Basically, you can pass the result of the function call to a 
function with an `auto ref` parameter and check whether that 
parameter is inferred as ref or not.


More information about the Digitalmars-d-learn mailing list