如何将具有多个参数的函数传递给期望只有一个参数的函数的子例程?
How to pass a function with multiple arguments to a subroutine that expects a function with only one argument?
我有一个子程序(最小示例)
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
。所以理想情况下,我想调用
call treatfunction(fun(:,a=a0), input=myinput, output=myoutput)
使用 gfortran-5
支持的 Fortran2003 功能,最优雅的方法是什么?
当然,我可以在 treatfunction
中插入一个可选的虚拟参数 a
并根据 [=] 使用 f(x)
或 f(x,a)
调用 f
22=] 在子例程的主体中。但是改子程序就不优雅了
在 Fortran 2008 中,您可以将内部函数作为参数传递,gfortran 支持它。
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
它是邪恶的,使用接口块。
我有一个子程序(最小示例)
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
。所以理想情况下,我想调用
call treatfunction(fun(:,a=a0), input=myinput, output=myoutput)
使用 gfortran-5
支持的 Fortran2003 功能,最优雅的方法是什么?
当然,我可以在 treatfunction
中插入一个可选的虚拟参数 a
并根据 [=] 使用 f(x)
或 f(x,a)
调用 f
22=] 在子例程的主体中。但是改子程序就不优雅了
在 Fortran 2008 中,您可以将内部函数作为参数传递,gfortran 支持它。
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
它是邪恶的,使用接口块。