[英]fortran subroutine: array of arbitrary type
I'm trying to write a subroutine to reverse the rows of an array. 我正在尝试编写一个子例程来反转数组的行。 The following works, but explicitly declares the type of its input arr. 以下工作,但显式声明其输入arr的类型。 Thus I'd need a separate subroutine to do the same thing for an array of type real. 因此,我需要一个单独的子例程来对real类型的数组执行相同的操作。 Surely there's a way to make it accept an array of arbitrary type - could someone help me with the syntax? 当然,有一种方法可以使它接受任意类型的数组-有人可以在语法方面帮助我吗? Thanks! 谢谢!
SUBROUTINE flipud(arr)
integer, dimension(:,:), intent(inout) :: arr
integer, dimension(:,:), allocatable :: tmp
integer i, j, nrow, ncol, ierr
nrow = size(arr, 1)
ncol = size(arr, 2)
allocate(tmp(nrow, ncol), STAT=ierr)
tmp(:,:) = arr(nrow:1:-1, :)
arr = tmp
deallocate(tmp)
END SUBROUTINE flipud
Fortran does not have the equivalent of C++ templates. Fortran没有等效的C ++模板。 You can create an interface with module procedures, as sketched below. 您可以使用模块过程创建接口,如下所示。 The code that is common to both subroutines could be placed in a file that is incorporated using the INCLUDE statement. 这两个子例程共有的代码可以放在使用INCLUDE语句合并的文件中。
module foo
interface fliupud
module procedure flipud_i,flipud_r
end interface flipud
contains
subroutine flipud_i(arr)
integer, dimension(:,:), intent(inout) :: arr
! body
end subroutine flipud_i
!
subroutine flipud_r(arr)
real, dimension(:,:), intent(inout) :: arr
! body
end subroutine flipud_r
end module foo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.