auto ref

Walter Bright newshound1 at digitalmars.com
Tue Dec 15 23:18:12 PST 2009


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); }



More information about the Digitalmars-d mailing list