delegate issue

captaindet via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 2 09:30:31 PDT 2014


On 2014-06-02 08:08, "Marc Schütz" <schuetzm at gmx.net>" wrote:
> On Monday, 2 June 2014 at 06:56:54 UTC, captaindet wrote:
>> hi,
>>
>> i stumbled upon something weird - it looks like a bug to me but
>> maybe it is a "feature" that is unclear to me.
>>
>> so i know i can declare function and delegate pointers at module level.
>> for function pointers, i can initialize with a lambda.
>> BUT for delegates i get an error - see below
>>
>> i found out that using module static this(){...} provides a workaround, but why is this necessary?
>>
>> also, if there is a good reason after all then the error message should make more sense.
>>
>> /det
>>
>> ps: i know there is a shorthand syntax for this.
>>
>> ----
>> module demo;
>>
>> int function(int) fn = function int(int){ return 42; };
>> // ok
>>
>> int delegate(int) dg = delegate int(int){ return 666; };
>> // demo.d(6): Error: non-constant nested delegate literal expression __dgliteral6
>>
>> void main(){}
>
> This doesn't work, because a delegate needs a context it can capture,
> which is available only inside of a function.
>
> The workaround is either, as Mr Smith suggests, to use a static
> constructor, or you can use std.functional.toDelegate() (probably,
> didn't test).

FWIW, tried toDelegate() and it does not work either:

--------
module demo2;
import std.functional : toDelegate;

int function(int) fn = function int(int){ return 42; };
// ok

int dg_def(int){ return 666; }
int delegate(int) dg = toDelegate(&dg_def);
// c:\D\DMD2\windows\bin\..\..\src\phobos\std\functional.d(758): Error: Cannot convert &int delegate(int a0) @system to void* at compile time
// demo2.d(8):        called from here: toDelegate(& dg_def)

void main(){}


More information about the Digitalmars-d-learn mailing list