What are the differences between these forms of function-like declarations ?

Timon Gehr timon.gehr at gmx.ch
Wed Sep 5 21:51:56 PDT 2012


On 09/06/2012 06:32 AM, Anderel Cerol wrote:
> auto fun = (para)=>{...};

This is the same as auto fun = (para){ return (){ ... }; };

The syntax is:

(params)=>expression

{...} // a function literal with body ...

Therefore (params)=>{...}

is the composition of two function literals.

> auto  fun = (para){...};

The types of function literals depend on the actual function bodies
(and their usage).
If the function bodies refer to an outer dynamic context, they are
deduced as delegate types, otherwise they are function pointer types.

(A delegate is a fat pointer that includes a function pointer and a
frame pointer to support eg. lexical closure.)

> auto fun = delegate(para){...};
> auto fun = function(para){...};

These disable the deduction and force either delegate or function
(compile time error, if the body of the function pointer literal
attempts to access an outer dynamic scope.)

> --------------------------------------------
> void on(void delegate(int)callback){...}
>
> on((para)=>{...});

This won't work, because the delegate return type is the type of some
function literal instead of void.

> on((para){...});

Should work if the body does not return a value.

> on(delegate(para){...});

Same here.

> on(function(para){...});

function pointers are incompatible with delegates.
std.functional.toDelegate can be used to create a delegate from a
function pointer if needed.

> --------------------------------------------
> some of them has the attribute @safe nothrow or @system,others
> don't .
> Is that inconsistency a intended design or not ?

Function literals infer @safe nothrow or @system. As long as you do not
provide the actual function bodies I cannot answer this.

> The additional attributes
> make some function parameter passing
> not work since they have different signature .
>

This is not what is happening, as explained above.




More information about the Digitalmars-d mailing list