auto ref and arrays

Jonathan M Davis jmdavisProg at gmx.com
Tue Nov 27 14:52:30 PST 2012


On Tuesday, November 27, 2012 14:44:51 Ali Çehreli wrote:
> On 11/27/2012 02:09 PM, Jack Applegame wrote:
> > I don't understand why auto ref doesn't work with arrays.
> > 
> > void test1(T)(auto ref const T[] val) {}
> > void test2(T)(auto ref const T val) {}
> > void main() {
> > int b;
> > test2(b); // OK
> > string a;
> > test1(a); // Error: cast(const(char[]))a is not an lvalue
> > }
> > 
> > Since a is mutable itself, compiler uses ref storage class.
> > cast(const(char[]))a isn't an lvalue, so it's impossible to pass it by
> > ref.
> > 
> > But cast(const int)b isn't an lvalue too. Why it's no errors in this case?
> 
> Sorry, I am not answering the question but is 'auto ref' is legal as a
> parameter? It is not documented.
> 
> On the other hand, 'auto ref' is a legal return type.

Yes, it's legal on function paramters - but only on templated functions. It 
was an attempt at solving the const& problem. It's supposed to take both 
lvalues and rvalues but not copy lvalues. I think that there's a decent chance 
that TDPL talks about it, but I'm not sure, though if it does, what it 
describes isn't quite what auto ref does at the moment, since the original 
idea for auto ref would have worked with non-templated functions, but Andrei 
and Walter miscommunicated on its intent, and it wasn't implemented that way 
(and would actually be problematic to implement that way).

As for the OP's question, I'd say that it looks like a bug. My guess is that a 
cast is being inserted as part of the auto ref implementation, and a cast does 
_not_ result in an lvalue, so that's why it would fail. I don't know why it 
thinks it needs a cast though.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list