Fortran:如何使多个过程共享同一个过程接口

Fortran: How to make multiple procedures share the same procedure interface

我的代码看起来像

subroutine sub1(f)
    interface
        function f(x)
            (description of f)
        end function f
    end interface

    (do something with f)
end subroutine sub1

subroutine sub2(f)
    interface
        function f(x)
            (description of f)
        end function f
    end interface

    (do something with f)
end subroutine sub2

然而,两个子例程sub1sub2 都为虚拟函数f 使用相同的接口。如何使这两个过程共享相同的接口(例如使用模块)?我必须使用过程指针吗?

您可以在模块中将此类可重用 "function types" 定义为 abstract interfaces:

module m
    implicit none
    abstract interface
        function der(x,y) result(yDot)
            real, intent(in) :: x, y
            real :: yDot
        end function
    end interface
end module

subroutine integrateEuler(derY,x0,xf,y)
    use m
    real, intent(in) :: x0, xf
    real, intent(inout) :: y
    procedure(der) :: derY
    ! code here
end subroutine

subroutine integrateRKF45(derY,x0,xf,y)
    use m
    real, intent(in) :: x0, xf
    real, intent(inout) :: y
    procedure(der) :: derY
    ! code here
end subroutine

不需要使用函数 pointers,但您可以用相同的方式声明它们:procedure(der), pointer :: funPtr => myFun