2011-02-18 76 views
4

如何才能在fortran 90中实现此目标?我有一个常规的接受功能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

我的第一个想法是使用一个过程指针,但后来我注意到你指定了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 

使用多个可选的子程序它可能成为一个有点复杂,但不是不可能的,我想。