我希望这不是一个太愚蠢的问题,但是是否有可能具有函数或子例程,我可以在其中传递数组的类型,例如
subroutine foo(array, arr_type)
implicit none
arr_type, dimension(:) :: array
*Do something with array*
end subroutine
还是我必须为每个可能arr_type(例如整数、双精度,...)编写一个子例程,并使用接口重载子例程?
是和不是...您可以使用接口将多个函数/子例程与不同的虚拟参数捆绑在一起:
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
我知道没有(简单)的可能性传递具有任意基本类型的数组。你可以看看transfer
- 但有龙;-)
你可以尝试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
但你最终可能会写出尽可能多的行,就像你遵循亚历山大·沃格特完全明智的方法一样。
编辑,在评论后
这种方法不会提供什么,因为 Fortran 没有在任何类型的类型层次结构中包含其内部类型,是一个代码,例如
select type (element=>array(1))
class is (number)
! Code for any type and kind of Fortran number
这将是有用的,但我不认为它很快就会发生。