Generalizing over function pointers and delegates

Bastiaan Veelo Bastiaan at Veelo.net
Fri Feb 15 17:59:14 UTC 2019


On Friday, 15 February 2019 at 17:28:45 UTC, H. S. Teoh wrote:
> On Fri, Feb 15, 2019 at 05:40:39PM +0100, ag0aep6g via 
> Digitalmars-d-learn wrote:
>> Your fun_to_dlg fails when the function has parameters.
>
> Yes. Delegates are basically syntactic sugar for a function 
> pointer with an implicit first parameter. I.e., a delegate like:
>
> 	int delegate(string) dg;
>
> is under the hood implemented as the equivalent of:
>
> 	struct _delegate {
> 		int function(T* context, string) funcptr;
> 		T* context;
> 		int opCall(string s) { return funcptr(context, s); }
> 	}
>
> where T is an appropriate context type, whether an aggregate 
> (struct / class) or an anonymous struct that closes over 
> whatever variables the delegate accesses in its containing 
> scope.
>
> For this reason, casting a function pointer to a delegate will 
> not work properly, because the first arguments and number of 
> parameters would not match.
>
>
> T

I love this forum!


More information about the Digitalmars-d-learn mailing list