【问题标题】:How to store a reference to a procedure in a Fortran derived type如何在 Fortran 派生类型中存储对过程的引用
【发布时间】:2018-06-20 23:56:29
【问题描述】:

我可以在 Fortran 类型中存储对过程的引用吗?

我的目标是通过将重复参数分组到一个类型中来减少 Fortran 子例程中的重复参数。但是 Fortran 不允许我为外部程序执行此操作。

这是我尝试做的一个简化示例:

module my_functions
    type mytype
        external :: f
    end type
contains
    subroutine fa()
        WRITE(*,*) "yiha"
    end subroutine

    subroutine fb(t)
        type(mytype) t
        call t%f()
    end subroutine
end module

program test
    use my_functions
    type(mytype) :: m
    m%f = fa
    call fb(m)
end program

然而 gfortran 给了我

     external :: f
                 1
Error: Unexpected attribute declaration statement at (1)

【问题讨论】:

  • 具体来说,我有一个对象,它依赖于几个用户提供的外部函数,我不想在每次调用该对象的方法时都传递所有这些函数。

标签: fortran


【解决方案1】:

派生类型可以将过程指针作为组件:

implicit none

type mytype
  procedure(), pointer, nopass :: f
end type

type(mytype) m

external fa
m%f => fa

call m%f()

end

这种类型有一个带有隐式接口的过程,稍后将其作为子例程引用。因为它有一个隐式接口,所以指针需要nopass 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    相关资源
    最近更新 更多