Call a function with a function pointer

Dicebot public at dicebot.lv
Thu Oct 10 11:54:44 PDT 2013


On Thursday, 10 October 2013 at 17:47:54 UTC, Namespace wrote:
> ----
> import std.stdio;
>
> void foo1(void function(void*) fp) { }
> void foo2(void function(int) fp) { }
> void foo3(void*) { }
>
> void main()
> {
> 	foo1((void* ptr) => ( assert(ptr is null) ));
> 	foo2((int a) => ( a + 1 )); /// Fails: Error: function foo2 
> (void function(int) fp) is not callable using argument types 
> (int function(int a) pure nothrow @safe)
> 	
> 	foo1(&foo3);
> 	
> 	void foo4(void function(void*) fp) { }
> 	foo1(&foo4); /// Fails: Error: function foo1 (void 
> function(void*) fp) is not callable using argument types (void 
> delegate(void function(void*) fp))
> }
> ----
> Can someone explain that to me?

You are using short lambda syntax "a => b". Here `b` is always 
return statement. It is equivalent to "(a) { return b; }". And 
your `foo2` signature expects lambda returning void, like "(a) { 
return; }"

Second error is DMD incompetence in deducing minimal required 
type of nested function. It always treats them as delegates (== 
having hidden context pointer) even if those do not refer any 
actual context. And plain lambdas are of course binary 
incompatible with delegates (closures) because of that extra 
pointer field.


More information about the Digitalmars-d-learn mailing list