February 16, 2007
Hello,

I have a question about using a template mixin to add a nested function to a class method, when the nested function references class member variables. For example:

class SomeClass
{
    int memberVar;
    void doSomething()
    {
        int localVar;
        mixin HelperFunction;	// see below
        helperFunction();
    }
}

template HelperFunction()
{
    void helperFunction()
    {
        localVar++;	// This works fine
        memberVar++;	// Error: need 'this' to access member memberVar
    }
}

I'm not sure why the mixed-in nested function can't access member variables of the enclosing class (it works if I just write the nested function directly inside the class method). Is this a bug, or (more likely) have I not fully grasped the ins and outs of using template mixins?

Thanks,
Gerald Stocker
February 16, 2007
On Fri, 16 Feb 2007 00:31:07 -0500, Gerald Stocker wrote:

> Hello,
> 
> I have a question about using a template mixin to add a nested function to a class method...

I have trouble with mixin templates too. I believe the effect you see is because the mixin introduces its own scope and you have to qualify reference that are outside the mixin.

However, the new mixin(Statement) might be useful to you ...

-------------
import std.stdio;
class SomeClass
{
     int memberVar;
     void doSomething()
     {
        int localVar;
        mixin(helperFunction);
        helperFunction();
     }
}

const char[] helperFunction = "
     void helperFunction()
     {
         localVar++;
         memberVar++;
     }
    ";
void main()
{
    SomeClass x = new SomeClass();
    x.doSomething();
    writefln("memberVar = %s", x.memberVar);
    x.doSomething();
    writefln("memberVar = %s", x.memberVar);
}
--------------



-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Justice for David Hicks!"
16/02/2007 4:49:50 PM
February 16, 2007
Derek Parnell wrote:
> On Fri, 16 Feb 2007 00:31:07 -0500, Gerald Stocker wrote:
> 
>> Hello,
>>
>> I have a question about using a template mixin to add a nested function to a class method...
> 
> I have trouble with mixin templates too. I believe the effect you see is
> because the mixin introduces its own scope and you have to qualify
> reference that are outside the mixin.
> 
> However, the new mixin(Statement) might be useful to you ...
> 

It is, thanks! It turns out several of the things I was trying (and sometimes failing) to do with template mixins make more sense as statment mixins.

--Gerald
Top | Discussion index | About this forum | D home