Thread overview
Templated Function pointers
Nov 29, 2012
js.mdnq
Nov 30, 2012
Ali Çehreli
Nov 30, 2012
js.mdnq
Nov 30, 2012
bearophile
November 29, 2012

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.

In C++ one can do this by using boosts binding's and function types.

For example, I want something like this

void function(F)(F) funcptr;

void Bind(T)(void function(T)(T) v)
{
    funcptr = v; // F is sort of deduced automatically as being T. Obviously problematic but effectively what I want to do.
}

This way I can bind to any function that takes a single type parameter and returns a void.


void function(F) myfuncptr;  // F is undefined
void myfunc(T)(T d) { }      //
myfuncptr = myfunc;

To do this using boost I would simply bind the parameter so myfuncptr would not depend on an arbitrary type.

I need a rather performant way to do this too.



November 30, 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

November 30, 2012
It seems one can accomplish this using delegates assigned by generic functions. The delegate will end hold holding the "state" of the function. It sort of acts like a binder. It seems to work but more testing needs to be done. I'm not sure how efficient it is or if there is a better way but basically it seems rather elegant(rather than trying to create some new type to deal with it).





November 30, 2012
js.mdnq:

> It seems one can accomplish this using delegates assigned by generic functions.

If you care so much for performance, when you work with D delegates it's useful to know the difference between static/scope delegates (that are just a fat pointer) and closures (that often induce a heap allocation).

Bye,
bearophile