How to pass a function with multiple arguments to

2019-01-20 13:33发布

I have a subroutine (minimal example)

subroutine treatfunction(f,input,output)
   external, real::f
   real, intent(in):: input
   real, intent(out):: output

   output = f(input) + f(1.0)  ! i.e. f has only one argument
end subroutine

and a function with two arguments

real function fun(x,a)
   real,intent(in)::x,a

Now for a given a fixed at runtime, I want to pass fun to treatfunction. So ideally, I would want to call something like

call treatfunction(fun(:,a=a0), input=myinput, output=myoutput)

What is the most elegant way of doing this with the Fortran2003 features gfortran-5 supports?

Of course, I could insert an optional dummy argument a in treatfunction and call f either with f(x) or f(x,a) depending on present(a) in the subroutine's body. But changing the subroutine is not elegant.

1条回答
老娘就宠你
2楼-- · 2019-01-20 13:53

In Fortran 2008 you can pass internal functions as arguments and gfortran supports it.

 subroutine calling()

   a0 = ...
   call treatfunction(wrapper, input=myinput, output=myoutput)
 contains
   real function wrapper(x)
     real, intent(in) :: x
     wrapper = fun(x,a0)
   end function
 end subroutine

BTW, I would stay away from external it is evil, use interface blocks.

查看更多
登录 后发表回答