Modify Function Pointer to Take Additional Parameters
jmh530 via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Feb 18 21:41:01 PST 2016
I'm trying to write a function that will adjust the parameters of
a function pointer.
In the code below, my goal is to call the function qux with a
variety of different function pointers (in the actual
application, I don't have the ability to modify qux). I created a
function foo that I thought would adjust it properly. The problem
is that the foo function converts the function pointer into a
delegate.
I was able to get something that works in this simple example by
introducing a delegate alias and an alternate definition of qux
that takes a delegate. However, in my actual application, I can't
modify what the equivalent of qux would take as parameters.
So I was just curious if there was any other alternative.
alias fp1 = int function(int x);
alias fp2 = int function(int x, int y);
auto foo(T)(T f)
{
static if (is(T == fp2))
return f;
else static if (is(T == fp1))
{
return (int x, int y) => f(x);
}
else
return 0;
}
int bar(int x)
{
return x;
}
int baz(int x, int y)
{
return x + y;
}
int qux(int x, int y, fp2 f)
{
return f(x, y);
}
void main()
{
import std.stdio : writeln;
auto foo_bar = foo(&bar);
writeln(qux(1, 2, foo_bar)); //compiler error
writeln(qux(1, 2, &baz));
}
More information about the Digitalmars-d-learn
mailing list