Comment #0 by bearophile_hugs — 2010-08-17T08:11:13Z
Few examples of 'auto ref' usage that I don't understand, so I mix them here.
This D2 code compiles and runs with no errors (DMD 2.048), showing that that 'f' is the version without 'ref':
int foo(T)(auto ref T[] arr) {
arr.length += 1;
return 0;
}
void main() {
foo([1]);
int[] a = [2];
foo(a);
auto f = &foo!int;
int[] b = [3];
f(b);
assert(b.length == 1);
}
How can I associate to 'f' the version with 'ref'?
----------------
If in that program I comment out the first line of the main:
int foo(T)(auto ref T[] arr) {
arr.length += 1;
return 0;
}
void main() {
//foo([1]);
int[] a = [2];
foo(a);
auto f = &foo!int;
int[] b = [3];
f(b);
assert(b.length == 1);
}
Then it asserts, b.length is now 2. So 'f' is the version with 'ref'.
----------------
If in the original program I comment out the whole first part of the main():
int foo(T)(auto ref T[] arr) {
arr.length += 1;
return 0;
}
void main() {
/*
foo([1]);
int[] a = [2];
foo(a);
*/
auto f = &foo!int;
int[] b = [3];
f(b);
assert(b.length == 1);
}
I receive error messages at compile-time (but I don't understand the first error message):
test.d(1): Error: auto can only be used for template function parameters
test.d(11): Error: template instance test9.foo!(int) error instantiating
Comment #1 by lt.infiltrator — 2015-12-09T09:38:49Z
I'm sure that you probably know this by now, but here goes.
============
int foo(T)(auto ref T[] arr) { // The auto is invalid as we already have ref T[] to specify the type
arr.length += 1;
return 0;
}
void main() {
foo([1]); // This call will not work because [1] is not an lvalue
int[] a = [2];
foo(a);
auto f = &foo!int;
int[] b = [3];
f(b);
assert(b.length == 1); // This needs to be changed to == 2 to pass on success
}
============
Modified working version:
============
int foo(T)(ref T[] arr) {
arr.length += 1;
return 0;
}
void main() {
int[] a = [2];
foo(a);
auto f = &foo!int;
int[] b = [3];
f(b);
assert(b.length == 2); // Changed to == 2 to pass on success
}
============
Comment #2 by ag0aep6g — 2015-12-09T17:45:14Z
(In reply to Infiltrator from comment #1)
> int foo(T)(auto ref T[] arr) { // The auto is invalid as we already have ref
> T[] to specify the type
The auto is fine. http://dlang.org/spec/template.html#auto-ref-parameters
That said, the compiler seems to behave differently now than when the bug was filed. `&foo!int` is rejected in all cases, now. I'm not sure what exactly the report is asking for, so this may or may not be good enough to close the issue.