Can I pass a function by parameter?

Jakob Ovrum via Digitalmars-d digitalmars-d at puremagic.com
Sun Sep 7 14:23:25 PDT 2014


On Sunday, 7 September 2014 at 21:02:16 UTC, John Colvin wrote:
> bool g(int n) { ... }
> f(arr, &g);

This will fail if `&g` is a function pointer, such as when `g` is 
declared at module-level scope. In that case, it has to be 
explicitly converted to a delegate:

---
import std.functional : toDelegate;

int f(in int[] arr, bool delegate(int) func);
bool g(int n) { ... }
f(arr, toDelegate(&g));
---

Alternatively, make `f` receive a function pointer instead of a 
delegate:

---
int f(in int[] arr, bool function(int) func);
bool g(int n) { ... }
f(arr, &g);
---


More information about the Digitalmars-d mailing list