Templated Function pointers

Ali Çehreli acehreli at yahoo.com
Thu Nov 29 19:51:45 PST 2012


On 11/29/2012 03:17 PM, js.mdnq wrote:
 >
 >
 > I need to store a templated function in a function pointer, how can I do
 > this?
 >
 >
 > e.g.,
 >
 > void function(double) myfuncptr;
 > void myfunc(double d) { }
 > myfuncptr = myfunc;
 >
 > Now I would like to use a template parameter instead of double.

std.functional may have something:

   http://dlang.org/phobos/std_functional.html

Are you looking for something like the following?

import std.traits;

auto myDelegate(F : T function(T), T)(F f)
     if (isFunctionPointer!F)  // <-- probably unnecessary
{
     return (T a) => f(a * 2);
}

double func_double(double d)
{
     return d;
}

int func_int(int i)
{
     return i;
}

void main()
{
     auto d = myDelegate(&func_double);
     auto i = myDelegate(&func_int);

     assert(d(1.5) == 3.0);
     assert(i(42) == 84);
}

Ali



More information about the Digitalmars-d-learn mailing list