Alias template parameters and runtime functions
bearophile
bearophileHUGS at lycos.com
Sun Oct 3 07:54:21 PDT 2010
Peter Alexander:
> class Foo
> {
> int[] data;
>
> int foo(int i) { return data[i]; }
>
> auto allFoo()
> {
> auto fun = (int i) { return foo(i); };
> // alternatively: auto fun = &this.foo; (same result)
> return map!(fun)(iota(data.length));
> }
> }
>
> This compiles, but gives you an access violation when you try to use it.
But that code works with dmd 2.049:
import std.algorithm: map, equal;
import std.range: iota;
class Foo {
int[] data;
this(int[] a) { this.data = a.dup; }
int foo(int i) { return data[i] * 2; }
auto allFoo1() {
auto fun = (int i) { return foo(i); };
return map!(fun)(iota(data.length));
}
auto allFoo2() {
return map!((int i){ return foo(i); })(iota(data.length));
}
}
void main() {
auto f = new Foo([1, 2, 3]);
assert(equal(f.allFoo1(), [2, 4, 6]));
assert(equal(f.allFoo2(), [2, 4, 6]));
}
Bye,
bearophile
More information about the Digitalmars-d
mailing list