usage of ref foreach with variadic functions fails with "cannot be ref"

Michael Coulombe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 11 19:34:19 PST 2017


On Saturday, 11 February 2017 at 15:02:11 UTC, error wrote:
> On Saturday, 11 February 2017 at 14:43:18 UTC, rikki cattermole 
> wrote:
>> Try:
>>
>> foreach(i, v; vars) {
>> 	vars[i] = ...;
>> }
>
> Perfect! Thanks so much - I wish that hint was in the 
> documentation for variadic functions, although I guess it 
> suggests an inefficiency in the compiler - since there would be 
> an additional copy of vars[i] created in v.

Do you have a complete code example that gives your error? I 
can't reproduce it (DMD v2.073.0):

int foo(T...)(T vars) {
     int i = 0;
     foreach(ref v ; vars) {
         v = 5;
         i += v;
     }
     return i;
}
void bar(T...)(ref T vars) {
     foreach(ref v ; vars) {
         v = 3;
     }
}
void main() {
     import std.stdio;
     int x = 7;
     bar(x);
     writeln(foo(4,x,8.2)); // 15, no errors
}


More information about the Digitalmars-d-learn mailing list