问题描述
我有一个子程序(最小的例子)
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
一个有两个参数的函数
real function fun(x,a)
real,intent(in)::x,a
现在对于在运行时固定的给定 a
,我想将 fun
传递给 treatfunction
.所以理想情况下,我想调用类似
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)
gfortran-5
支持的 Fortran2003 功能最优雅的方式是什么?
What is the most elegant way of doing this with the Fortran2003 features gfortran-5
supports?
当然,我可以在 treatfunction
中插入一个可选的虚拟参数 a
并使用 f(x)f
/code> 或 f(x,a)
取决于子例程主体中的 present(a)
.但是改变子程序并不优雅.
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.
推荐答案
在 Fortran 2008 中,您可以将内部函数作为参数传递,并且 gfortran 支持它.
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
顺便说一句,我会远离 external
这是邪恶的,使用界面块.
BTW, I would stay away from external
it is evil, use interface blocks.
这篇关于如何将具有多个参数的函数传递给期望只有一个参数的函数的子例程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!