Is the address-of operator (&) really needed?

Jonathan M Davis jmdavisProg at gmx.com
Fri Jun 1 13:03:35 PDT 2012


On Friday, June 01, 2012 21:48:01 Artur Skawina wrote:
> On 06/01/12 21:18, Jonathan M Davis wrote:
> >>> 3. ref doesn't work with variadic templates very well. Take a
> >>> look a
> >>> std.getopt.getopt. It takes pointers, not refs, and there isn't
> >>> a way to make
> >>> it take refs.
> >> 
> >> Is it because getopt() is a C function? If it is see my reply to
> >> your point #1. I'll admit I do not know enough D to understand
> >> what you are saying, some explanation will be helpful.
> > 
> > It's not a C function. It's a variadic template. It's instantiated with
> > whatever types it's given. It's literally _impossible_ to use ref with
> > that
> > sort of function. So, if you want it to take the variable and write to it,
> > you have to pass a pointer to it.
> 
> import std.stdio;
> 
> void go(A...)(auto ref A a) {
> a[0] = 42;
> a[1].y--;
> }
> 
> struct S { int y; }
> 
> void main() {
> int x;
> S s;
> 
> go(x, s);
> 
> writeln(x, " ", s);
> }

auto ref is _completely_ different from ref. The compiler chooses whether to 
pass by ref or not with the idea that it will pick whatever is most efficient 
for that type, but it's implementation-dependent whether something will be 
passed by ref or not. And using ref is no solution, because then _all_ of the 
arguments must be lvalues. If you want a function to take an arbitrary set of 
arguments where some of them are passed by ref and others not, you _can't do 
it_. You have to use pointers instead, because the types of all of the 
parameters are inferred from the arguments, and nothing ever gets inferred as 
ref, because ref is not a type constructor.

- Jonathan M Davis


More information about the Digitalmars-d mailing list