Optional routines in Fortran 90

How can I achieve this goal in fortran 90? I have a function accepting function

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

Now I want the subroutine to be optional

 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 

Now, if mysub was a standard var variable, I could do something like

  if (present(var)) then l_var = var else l_var = <default value> endif 

but as far as I know, I cannot do the same for the extra routine. In practice, this is not possible.

 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 

because you cannot declare l_mysub. Is this possible with some kind of trick that I don't know about? Yes of course i can do

  if (present(mysub)) then call mysub(bar) else call default(bar) endif 

but my case is more complicated, and I would have to hang this check. Think that I have three optional routines that I can pass.

+4
source share
1 answer

My first thought was to use a procedure pointer, but then I noticed that you specified fortran 90, so this is not an option.
How about creating a wrapper routine for the original foo that calls it with the given routine, if one is specified, or using default ? Something like this (untested):

 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 

With a few optional routines, it can get a little complicated, but not impossible, I think.

+1
source

Source: https://habr.com/ru/post/1340316/


All Articles