【问题标题】:The name of a subroutine can be a variable in Fortran? [duplicate]子程序的名称可以是 Fortran 中的变量吗? [复制]
【发布时间】:2015-07-30 06:37:53
【问题描述】:

我想知道 Fortran 中是否有类似的东西。当然这个例子不能编译,但我想你能明白。

program test
    character(1):: sub

    sub='A'
    call sub

    sub='B'
    call sub
end program

subroutine A
    print*,'OK! A'
end subroutine A

subroutine B
    print*,'OK! B'
end subroutine B

【问题讨论】:

  • 如果它不能编译,那么它似乎不能工作。你不是在回答你自己的问题吗?
  • 您是在问“可以子例程的名称是 FORTRAN 中的变量吗?”如果没有,请提供minimal, complete, and verifiable example。请阅读“How to Ask”了解有关如何提问的更多提示。
  • 您不能根据子例程名称进行调用,但您可以使用过程指针代替:参见stackoverflow.com/questions/8612466/…。这个问题有多大用处实际上取决于你想做什么。

标签: fortran fortran90 subroutine


【解决方案1】:

您无法通过设置字符变量来完成此操作,但您可以使用过程指针来完成此操作。我已经稍微修改了你的例子来实现它。见:

program test
 implicit none

 abstract interface
    subroutine no_args
    end subroutine
 end interface

 procedure(no_args), pointer :: sub => null()

 sub => A
 call sub

 sub => B
 call sub

contains

subroutine A
 implicit none
 print *,"OK! A"
end subroutine

subroutine B
 implicit none
 print *,"OK! B"
end subroutine

end program

变化是:

  • 为过程指针定义一个接口
  • sub 声明为指向该抽象接口的过程指针

然后您可以将sub 分配给不带参数的子例程(因为这是接口所说的),并按照您的设想通过sub 调用它们。

【讨论】:

  • 这就是我要找的。谢谢你们的cmets。
【解决方案2】:

您可以获得的最接近的是函数/过程指针,但那将是 fortran-2003。基本上,给定输入“A”或“B”,您将指针设置为指向subroutine Asubroutine B。更多详情How to alias a function name in Fortran

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多