toDelegate

Convert a callable to a delegate with the same parameter list and return type, avoiding heap allocations and use of auxiliary storage.

toDelegate
(
F
)
(
auto ref F fp
)
if ()

Parameters

fp F

a function pointer or an aggregate type with opCall defined.

Return Value

Type: auto

A delegate with the context pointer pointing to nothing.

Bugs

  • Does not work with @safe functions.
  • Ignores C-style / D-style variadic arguments.

Examples

void doStuff() {
    writeln("Hello, world.");
}

void runDelegate(void delegate() myDelegate) {
    myDelegate();
}

auto delegateToPass = toDelegate(&doStuff);
runDelegate(delegateToPass);  // Calls doStuff, prints "Hello, world."
static int inc(ref uint num) {
    num++;
    return 8675309;
}

uint myNum = 0;
auto incMyNumDel = toDelegate(&inc);
auto returnVal = incMyNumDel(myNum);
assert(myNum == 1);

Meta

Suggestion Box / Bug Report