Fortran 90中的可选子程序

4
我该如何在Fortran 90中实现这个目标?我有一个接受函数的例程。
subroutine foo(bar, mysub)
   integer, intent(in) :: bar
   interface
      subroutine mysub(x)
         integer :: x
      end subroutine
   end interface

   call mysub(bar)

end subroutine

现在我希望这个例程是可选的。

subroutine foo(bar, mysub)
   integer, intent(in) :: bar
   interface
      subroutine mysub(x)
         integer :: x
      end subroutine
   end interface
   optional :: mysub

   call mysub(bar)

end subroutine

现在,如果我的 mysub 是一个标准变量 var,我可以像这样做:
 if (present(var)) then
     l_var = var
 else
     l_var = <default value>
 endif

但据我所知,我无法对可选子程序执行相同的操作。实际上这是不可能的。

subroutine foo(bar, mysub)
   integer, intent(in) :: bar
   interface
      subroutine mysub(x)
         integer :: x
      end subroutine
   end interface
   optional :: mysub

   if (present(mysub)) then
       l_mysub = mysub
   else
       l_mysub = default
   endif

   call mysub(bar)

end subroutine

因为你无法声明l_mysub。有没有一些我不知道的技巧可以做到这一点?是的,当然我可以做。
   if (present(mysub)) then
       call mysub(bar)
   else
       call default(bar)
   endif

但我的情况更为复杂,我需要在每个地方都进行这个检查。考虑到我有三个可选的子程序可以传递。

1个回答

1

我的第一个想法是使用过程指针,但是我注意到你指定了Fortran 90,所以这不是一个选项。
那么,为您的原始foo创建一个包装子程序如何?如果指定了给定的子程序,则调用它,否则使用default。类似于这样(未经测试):

subroutine foo_wrap(bar, mysub)
  integer, intent(in) :: bar
  interface
    subroutine mysub(x)
      integer :: x
    end subroutine mysub
  end interface
  optional :: mysub

  if (present(mysub)) then
    call foo(bar, mysub)
  else
    call foo(bar, default)
  endif
end subroutine foo_wrap  

有多个可选子程序可能会变得有点复杂,但我认为并不是不可能的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接