delegates, functions, and literals confusion

CJS Prometheus85 at hotmail.com
Wed Jul 3 23:43:09 PDT 2013


Confusion over delegates seems to be a somewhat common topic, 
judging from 
http://forum.dlang.org/thread/jbkahhlvevgectisdzdg@forum.dlang.org 
and 
http://stackoverflow.com/questions/6431884/function-and-delegate-literals-in-d. 
I'm also somewhat confused by functions vs. function literals and 
how to pass them around.

In my case I'm trying to figure out the best way to pass 
functions to other fundtions. So I wrote the following toy code 
to see what the compiler would do. I'm trying to understand why 
the compiler emitted errors on the code below (shown w/ 
comments). Any insight/suggestions on better ways to pass 
functions around would also be appreciated.

import std.datetime;
import std.stdio;


void f(int delegate(int) h){
     writefln("h(0)=%d", h(0));
}

void g(int function (int) h){
     writefln("h(0)=%d", h(0));
}

void main(){

     int foo(int a){ return a+6;}
     auto bah = function int(int b){ return b+7;};

     f(foo); //error
     f(&foo);
     f(bah); //error
     f(&bah); // error

     g(foo); //error
     g(&foo); //error
     g(bah);
     g(&bah); //error

}


More information about the Digitalmars-d-learn mailing list