【问题标题】:How to pass a function with multiple arguments to a subroutine that expects a function with only one argument?如何将具有多个参数的函数传递给期望只有一个参数的函数的子例程?
【发布时间】:2015-07-03 22:03:30
【问题描述】:

我有一个子程序(最小的例子)

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,具体取决于子例程主体中的present(a)。但是改变子程序并不优雅。

【问题讨论】:

  • 您可以使用带有一个参数的包装函数来执行此操作,然后进一步调用。比如在stackoverflow.com/q/9982657.
  • 是的,我还记得 thar 过去有类似的东西,但很难找到。

标签: fortran gfortran


【解决方案1】:

在 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 这是邪恶的,使用界面块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-22
    • 2020-01-13
    • 1970-01-01
    • 2011-03-09
    • 2022-06-20
    • 2014-12-04
    • 2012-02-18
    相关资源
    最近更新 更多