auto ref and arrays

Dan dbdavidson at yahoo.com
Wed Nov 28 03:49:05 PST 2012


On Tuesday, 27 November 2012 at 22:09:21 UTC, 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?

I thought with auto ref you dispense with the const since it 
figures it out.
The below seems to work.

Thanks,
Dan

import std.traits;
import std.stdio;

void test1(T)(auto ref T val) if(!isArray!T) {
   writeln("Nonarray ", typeid(typeof(val)));
}
void test1(T)(auto ref T val) if(isArray!T) {
   writeln("Array ", typeid(typeof(val)));
}

void main() {
   string a;
   const(string) b = "string that never changes";
   test1(a);
   test1(b);

   int[] x;
   test1(x);
   int y;
   test1(y);
}


More information about the Digitalmars-d-learn mailing list