Modify Function Pointer to Take Additional Parameters
Yuxuan Shui via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Feb 19 13:57:46 PST 2016
On Friday, 19 February 2016 at 20:45:23 UTC, jmh530 wrote:
> On Friday, 19 February 2016 at 15:00:51 UTC, jmh530 wrote:
>>
>> This works.
>>
>> But when I re-write foo to take that into account as in below,
>> I get an error that I can't implicitly convert int
>> function(int x) to int function(int x, int y).
>
>
> I don't think I had looked at what you had done carefully
> enough. Basically, you just define a new function and take a
> function pointer of that. That might be a brute force solution.
>
> I tried to use a cast (below) to modify the function pointer,
> but it is printing the second number instead of the first. I
> find this behavior strange...
>
> int foo(int x)
> {
> return x;
> }
>
> void main()
> {
> import std.stdio : writeln;
>
> auto foo_ = cast(int function(int x, int y)) &foo;
>
> writeln(foo_(1, 200)); //prints 200
> }
I don't think it's safe to convert between function pointer with
different number of arguments... It's possible to mess up the
stack frame.
Also '(int x, int y)=>f(x)' is clearly a delegate because it
refers to local variable 'f', you can't just cast it to 'int
function(int, int)'.
More information about the Digitalmars-d-learn
mailing list