auto ref
Mikhail Dahl
mikhail at nevertobeknown.com
Tue Dec 15 23:37:57 PST 2009
On 16/12/2009 07:18, Walter Bright wrote:
> There's a need in generic code to have a function take a parameter by
> ref if it is an lvalue, and by value if it is an rvalue. This can be
> addressed by making it a template using auto ref:
>
> T foo(T)(auto ref T x) { ... }
>
> foo(3) // call by value
> int y;
> foo(y) // call by reference
>
> There is also a need to 'transmit' the ref'ness to the return value.
> This can be done with auto ref:
>
> auto ref foo(T)(auto ref T x) { return x; }
>
> foo(3) => int foo(int x)
> foo(y) => ref int foo(ref int x)
>
> This means that the generic forwarding function would look like:
>
> auto ref foo(alias F, T...)(auto ref T args) { return F(args); }
Just to confirm (I'm just getting into D, so I don't know much about the
language, still learning), but the idea is to apply 'auto' not only to
types but also to storage classes? As in 'automatically apply ref in the
case of lvalue'?
If so I'm a little confused by 'auto ref foo(...' - if auto ref here is
also simply an 'apply ref in the case of lvalue', then where is the
return type being inferred from?
Dahl
More information about the Digitalmars-d
mailing list