How to provide this arg or functor for algorithm?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Aug 16 16:05:39 PDT 2015
On 08/16/2015 03:36 PM, cym13 wrote:
> On Sunday, 16 August 2015 at 22:22:07 UTC, Ali Çehreli wrote:
>>
>> // HERE:
>> // Error: function deneme.func @nogc function allocates
>> // a closure with the GC
>> @nogc auto func(uint[] arr, DelegateRef d)
>> {
>> return arr.map!(a => d.d(a));
>> }
>
> Aren't you making another delegate in the map by using "=>" that needs
> to allocate because it uses 'd' which is out of its scope?
I did not see that at all. :) I've finally gotten it to work by stepping
into template realm where the compiler is a master of attributes: :)
import std.stdio;
import std.range;
import std.algorithm;
struct Caller
{
this(uint context) {
_context = context;
}
// ADDED pure
pure uint method(uint value) {
return _context * value;
}
uint _context;
}
// Now the type of d is a template parameter
@nogc auto func(Func)(uint[] arr, Func d)
{
return arr.map!(d);
}
void main(string[] args)
{
uint[] arr = [1,2,3];
uint context = 2;
auto c = Caller(context);
auto d = &c.method;
writeln(func(arr, d));
}
Prints:
[2, 4, 6]
Ali
More information about the Digitalmars-d-learn
mailing list