Bug 19531 – Function pointers should be allowed as template arguments
Status
RESOLVED
Resolution
WORKSFORME
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2018-12-31T05:27:44Z
Last change time
2018-12-31T06:36:31Z
Assigned to
No Owner
Creator
Victor Porton
Comments
Comment #0 by porton — 2018-12-31T05:27:44Z
Function pointers should be allowed as template arguments.
Comment #1 by dhasenan — 2018-12-31T06:36:31Z
If you need to pass a function pointer, which is a runtime value, by value to a template function, you can pass it as an argument to the function instead of the template:
void foo(T)(T fn) if (is(T == delegate))
{
fn();
}
foo(() => writeln("hi"));
If you need to expose a function as a symbol to a template to be used at compile time, you can pass it as a symbol argument to the template. The parameter is declared as "alias fn" instead of just "fn":
void foo(alias fn)()
{
fn();
}
foo!(() => writeln("hi"));
If you need to expose a function pointer to a template, you can do that by exposing a variable that holds that function pointer to the template as a symbol:
void foo(alias fn)()
{
fn();
}
void bar() { writeln("bar"); }
auto functionPointer = &bar;
foo!functionPointer();
Most of the time, you can make things work the way you want just by omitting &.