function argument accepting function or delegate?

Jon D via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jan 16 22:27:41 PST 2016


My underlying question is how to compose functions taking 
functions as arguments, while allowing the caller the flexibility 
to pass either a function or delegate.

Simply declaring an argument as either a function or delegate 
seems to prohibit the other. Overloading works. Are there better 
ways?

An example:

auto callIntFn (int function(int) f, int x) { return f(x); }
auto callIntDel (int delegate(int) f, int x) { return f(x); }
auto callIntFnOrDel (int delegate(int) f, int x) { return f(x); }
auto callIntFnOrDel (int function(int) f, int x) { return f(x); }

void main(string[] args) {
     alias AddN = int delegate(int);
     AddN makeAddN(int n) { return x => x + n; }

     auto addTwo = makeAddN(2);                // Delegate
     int function(int) addThree = x => x + 3;  // Function

     // assert(callIntFn(addTwo, 4) == 6);     // Compile error
     // assert(callIntDel(addThree, 4) == 7);  // Compile error
     assert(callIntDel(addTwo, 4) == 6);
     assert(callIntFn(addThree, 4) == 7);
     assert(callIntFnOrDel(addTwo, 4) == 6);
     assert(callIntFnOrDel(addThree, 4) == 7);
}

---Jon


More information about the Digitalmars-d-learn mailing list