Call a function with a function pointer

Artur Skawina art.08.09 at gmail.com
Fri Oct 11 08:55:05 PDT 2013


On 10/10/13 20:54, Dicebot wrote:
> 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))
>> }
>> ----
> 
> 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.

It's probably not just "incompetence" (the compiler is able to figure this
out in other contexts), but a deliberate choice. Having function types
depend on their bodies would not be a good idea. Eg

    int c;
    auto f() {
       int a = 42;
       int f1() { return a; }
       int f2() { return 0; }
       return !c?&f1:&f2;
    }

Mark f2 as 'static' and this code will no longer compile. If that would
be done automatically then you'd have to 'undo' it manually, which would
cause even more problems (consider generic code, which isn't prepared
to handle this).

artur

[1] at least without other language improvements; enabling overloading on
    'static', plus a few other enhancements, would change the picture.


More information about the Digitalmars-d-learn mailing list