Generalizing over function pointers and delegates

ag0aep6g anonymous at example.com
Fri Feb 15 16:40:39 UTC 2019


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;
> }
> ```
[...]
> This may be preferable to the overload, depending on the number of calls 
> like this. But since this is allowed and working, why can't it be done 
> automatically? Or, when implicit conversion is dangerous, why doesn't a 
> cast exist to the effect of my template? Have I overlooked an easier way 
> of doing this?

Your fun_to_dlg fails when the function has parameters.

As far as I see, it would be possible make the conversion would work by 
changing how a delegate's context is passed [1]. But I didn't pursue 
that idea further, and no one else picked it up either.

[1] https://forum.dlang.org/post/ofc0lj$2u4h$1@digitalmars.com


More information about the Digitalmars-d-learn mailing list