【问题标题】:Arbitray variable/array type in fortran functions/subroutinesfortran函数/子程序中的任意变量/数组类型
【发布时间】:2014-01-14 09:08:01
【问题描述】:

我希望这不是一个太愚蠢的问题,但是否有可能有函数或子例程,我可以在其中传递数组的类型,例如

subroutine foo(array, arr_type)
implicit none
arr_type, dimension(:) :: array

*Do something with array* 
end subroutine

或者我是否必须为每个可能的 arr_type(例如整数、双精度、...)编写一个子例程并使用接口重载子例程?

【问题讨论】:

    标签: variables fortran subroutine


    【解决方案1】:

    是和否...您可以使用接口将多个函数/子例程与不同的虚拟参数捆绑在一起:

    module foos
      interface foo
        module procedure foo_real
        module procedure foo_int
      end interface
    
    contains
    
      subroutine foo_real( a )
        implicit none
        real,intent(inout) :: a(:)
    
        ! ...
      end subroutine
    
      subroutine foo_int( a )
        implicit none
        integer,intent(inout) :: a(:)
    
        ! ...
      end subroutine
    end module
    

    我知道没有(简单)可能传递任意 basic 类型的数组。你可以看看transfer - 但是有龙;-)

    【讨论】:

      【解决方案2】:

      您可以试验 Fortran 2003 的无限多态性。写你的子程序有点像这样:

      subroutine foo(array)
      implicit none
      class(*), dimension(:) :: array
      
      ! Do something with array
      
      end subroutine
      

      从缩写代码的角度来看,这不会为您节省太多,因为您可能不得不编写类似的东西

      use, intrinsic :: iso_fortran_env, only : real32, real64
      .
      .
      .
      select type (element=>array(1))
      type is (real(real32))
          ! Code for 32-bit reals
      type is (real(real64))
          ! Code for 64-bit reals
      type is (integer)
          ! Code for integers of default kind
      class is (shape)
          ! Code for shapes
      class default
          ! Sweep up everything else
      end select
      

      但你最终可能会写出尽可能多的行,就像你遵循 Alexander Vogt 完全明智的方法一样。

      编辑,在 cmets 之后

      由于 Fortran 不将其内在类型包含在任何类型的类型层次结构中,这种方法无法实现的是如下代码

      select type (element=>array(1))
      class is (number)
          ! Code for any type and kind of Fortran number
      

      这会很有用,但我认为它不会很快发生。

      【讨论】:

      • 我将测试这种方法。根据问题,它可能会稍微缩短代码,因为某些操作和功能不明确依赖于类型,例如。加号或减号。并且只需要调整一些部分
      • 偶数 + 和 - 取决于类型。事实上,几乎所有事情都是如此。还有一种使用include作为穷人模板objectmix.com/fortran/378796-fortran-templates-5.html的技术。
      • @VladimirF Modern Fortran in Practice by Arjen Markus 也有一个很好的例子(第 73-75 页)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 2017-07-19
      相关资源
      最近更新 更多