How to get the "this" ptr of a lambda inside the lambda?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 19 08:58:49 PDT 2016


On 7/19/16 11:25 AM, Rufus Smith wrote:
> On Tuesday, 19 July 2016 at 06:46:44 UTC, Mike Parker wrote:
>> On Tuesday, 19 July 2016 at 06:32:32 UTC, Rufus Smith wrote:
>>> Error: 'this' is only defined in non-static member functions, not
>>> __lambda2
>>>
>>> Lambda's are delegates and delegates have a "this" type of pointer. I
>>> would like to get at it inside the lambda to check for some things.
>>> I'm doing some funky stuff. I'm not concerned about the scope or what
>>> this actually pointers to or anything like that, just need it's value
>>> for debugging.
>>>
>>
>> No, delegates do not have a "this" type of pointer. "this" is an
>> implicit function parameter in a class or struct member function.
>> Delegates have no such thing. The only generic way I know of to get at
>> a delegate's function pointer inside the implementation is to
>> explicitly add the pointer type to the parameter list as part of the
>> declaration and pass it as an argument when you call the delegate.
>
> Delegates do have a this, they have a context pointer that is implicitly
> passed and used to access the outside context. It is no different than
> methods. Just because the explicit implementation details are different
> does not change the underlying meaning.
>

I think what Mike may be alluding to is that there is no name for the 
stack frame pointer you can use. There is no 'this' pointer that you can 
get at (even though it can be passed).

Also note that lambdas are not necessarily delegates, they could be 
straight function pointers if they don't need a context:

void main()
{
     int a;
     pragma(msg, typeof((int b) => b * 2)); // int function(int b) pure 
nothrow @nogc @safe
     pragma(msg, typeof(() => a * 2)); // int delegate() pure nothrow 
@nogc @safe
}

A question to ask is, why do you need it?

-Steve


More information about the Digitalmars-d-learn mailing list