Generalizing over function pointers and delegates
H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Feb 15 17:28:45 UTC 2019
On Fri, Feb 15, 2019 at 05:40:39PM +0100, ag0aep6g via Digitalmars-d-learn wrote:
> On 15.02.19 15:20, Bastiaan Veelo wrote:
> > Exploiting this, it is possible to explicitly convert a function
> > pointer into a delegate [2]:
> > ```
> > Ret delegate(Args args) fun_to_dlg(Ret, Args...)(Ret function(Args args)
> > fun)
> > {
> > Ret delegate(Args) dlg;
> > dlg.funcptr = fun;
> > return dlg;
> > }
> > ```
[...]
> 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
--
Without outlines, life would be pointless.
More information about the Digitalmars-d-learn
mailing list