[Issue 19531] Function pointers should be allowed as template arguments

d-bugmail at puremagic.com d-bugmail at puremagic.com
Mon Dec 31 06:36:31 UTC 2018


https://issues.dlang.org/show_bug.cgi?id=19531

Neia Neutuladh <dhasenan at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
                 CC|                            |dhasenan at gmail.com
         Resolution|---                         |WORKSFORME

--- Comment #1 from Neia Neutuladh <dhasenan at gmail.com> ---
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 &.

--


More information about the Digitalmars-d-bugs mailing list