Function names and lambdas

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Apr 6 11:45:26 PDT 2017


On 04/06/2017 11:37 AM, Russel Winder via Digitalmars-d-learn wrote:
> I am used to a function name being a reference to the function body,
> cf. lots of other languages. However D rejects:
>
> 	iterative
>
> as a thing can put in an array, it requires:
>
> 	(n) => iterative(n)
>
> Presumably this introduces inefficiency at run time? I.e. the extra
> level of indirection is not compiled away?
>

I think it's just a design choice. C implicitly converts the name of the 
function to a pointer to that function. D requires the explicit & operator:

alias Func = int function(int);

int foo(int i) {
     return i;
}

void main() {
     Func[] funcs = [ &foo ];
}

Close to what you mentioned, name of the function can be used as an 
alias template parameter:

void bar(alias func)() {
     func(42);
}

int foo(int i) {
     return i;
}

void main() {
     bar!foo();
}

Ali



More information about the Digitalmars-d-learn mailing list