Function Literals

Falk Henrich schreibmalwieder at hammerfort.de
Wed Mar 14 13:57:59 PDT 2007


Walter Bright wrote:

> Falk Henrich wrote:
>> int abc(int delegate(long i));
>> void test()
>> {   int b = 3;
>>     abc( (long c) { return 6 + b; } );
>> }
>> 
>> My question is: If the compiler can infer the return type of the
>> anonymous function, how come it can't infer the type of the parameter c?
>> Forgive me if this is too stupid a question, but I thought: if the
>> compiler knows the signature of abc it has to be clear that c is of type
>> long.
> 
> The problem is it doesn't know the function signature of abc, since abc
> may be overloaded, and may even be a function template.

The D compiler and I agree with you that given a situation like this:

int abc(int delegate(int) f) {return f(1);}
int abc(int delegate(real) f) {return f(0);}
int test() {
  return abc( (real c) {
      if (c >= 0)
        return +1;
      else
        return -1;
    } );
}

some kind of type annotation is needed. But this leads me to two related
(newbie-type) questions:

1.) Would it be possible to make the type annotation optional, so the
compiler throws an error if it gets confused and accepts the code if there
is no ambiguity?

2.) Does the D compiler consider return types at all? The code
int huhu() { return 5; }
double huhu() { return 5; }
leads to a conflict (like usual in C, C++, and Java). Therefore, I suspect,
it doesn't.

Maybe I missed something obvious again...

Falk




More information about the Digitalmars-d mailing list