Delegate function access to classes local variable

Colin Grogan grogan.colin at gmail.com
Fri Nov 8 05:18:04 PST 2013


On Friday, 8 November 2013 at 13:10:10 UTC, Dicebot wrote:
> On Friday, 8 November 2013 at 12:43:37 UTC, Colin Grogan wrote:
>> import std.stdio;
>> void main()
>> {
>> 	Column!string col1 = new Column!string( {return "test"; }, 
>> "Hello, ");
>> 	Column!string col2 = new Column!string( {return vars[0]; }, 
>> "World"); // Compilation fail!! Delegate cant see vars[0]
>> 	writef("%s", col1.nextValue);
>> 	writefln("%s", col2.nextValue);
>> // I want it to print "Hello, World" here
>> }
>
> Delegate refers to context it was created in. Your delegates 
> are created in `main()` scope/context and thus can only access 
> its stack frame. You can't access caller context from delegates.

Ok, that clarifies that then :(

Is there any alternative to using delegates for this behaviour? 
i.e. passing a function at object construct time, and let that 
function have access to the objects members?


More information about the Digitalmars-d-learn mailing list