implicitly convert function pointers to delegates

KennyTM~ kennytm at gmail.com
Sun Oct 26 11:11:37 PDT 2008


Moritz Warning wrote:
> Hi,
> 
> some people discovered that functions can be wrapped into delegates 
> without allocation.
> 
> Here is one out of several similar solutions:
> 
> R delegate(T) toDg(R, T...)(R function(T) fp) {
>     struct dg {
>         R opCall(T t) {
>             return (cast(R function(T)) this) (t);
>         }
>     }
>     R delegate(T) t;
>     t.ptr = fp;
>     t.funcptr = &dg.opCall;
>     return t;
> }
> 
> I would like to ask if we can get this into the language?
> It would make working with delegates and function pointers much more 
> easier when function pointers implicitly convert to delegates when they 
> "have to".

vote++ for implicit conversion. An FP can be *safely* converted to any DGs.

BTW,

   alias float delegate (in float) DG;

   float area (in float radius) {
	float r2 = radius * radius;
	return 3.1415926535 * radius;
   }

   DG x;
   x.ptr = null;
   x.funcptr = &area;
   // writefln(typeof(x.funcptr).stringof); // ensure it's an FP not DG.
   writefln(x(10)); // writes 314.159 without any error.


Why this simpler solution is not used? The function pointer can't touch 
the frame pointer anyway (an FP cannot access stuff outside its scope).



More information about the Digitalmars-d mailing list