问题描述
我有一个子程序(最简单的例子)$ b $ pre $ $ $ c $子程序处理函数$ f $输入$输出$外部, real :: f
real,intent(in):: input
real,intent(out):: output
output = f(input)+ f(1.0)!即f只有一个参数
结束子程序
和一个带两个参数的函数
当然,我可以在处理函数中插入一个可选的伪参数 a 或 f(x,c $ c>)并调用 f a)取决于子程序正文中的 present(a)。但是改变子程序并不优雅。
解决方案在Fortran 2008中,您可以将内部函数作为参数传递并且gfortran支持它。
$ b $调用处理函数(wrapper,input = myinput,output = myoutput)
包含
真实函数包装(x)
真实,意图(in):: x
包装= fun(x,a0)
end函数
结束子程序
顺便说一句,我会远离外部它是邪恶的,使用接口块。
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.
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.
这篇关于如何将一个具有多个参数的函数传递给一个只有一个参数的子程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!