Array of derived type: select entry

荒凉一梦 提交于 2019-12-05 18:28:57
M. S. B.

For the array case, instead of passing in arguments array and index i, you could pass in the single argument array (i). When you switch to having the derived type, similarly you could pass in variable_of_type % element rather than passing in the entire variable_of_type and somehow instructing the procedure which subelement it is supposed to work on. If the code needs to be different for the different types of elements (e.g., logical, integer, real), then you could write specific procedures for each, but call then with a common name via a generic interface block. The compiler has to be able to distinguish the procedures of the generic interface block by some characteristic of the arguments, here their type. For a code example in which the distinguishing characteristic is array rank see how to write wrapper for 'allocate'

EDIT: example code. does this do what you want?

module my_subs

   implicit none

   interface my_sum
      module procedure sum_real, sum_int
   end interface my_sum

contains

subroutine sum_real (array, tot)
   real, dimension(:), intent (in) :: array
   real, intent (out) :: tot
   integer :: i

   tot = 1.0
   do i=1, size (array)
      tot = tot * array (i)
   end do
end subroutine sum_real

subroutine sum_int (array, tot)
   integer, dimension(:), intent (in) :: array
   integer, intent (out) :: tot
   integer :: i

   tot = 0
   do i=1, size (array)
      tot = tot + array (i)
   end do
end subroutine sum_int

end module my_subs


program test_dt

use my_subs

implicit none

type my_type
   integer weight
   real length
end type my_type

type (my_type), dimension (:), allocatable :: people
type (my_type) :: answer

allocate (people (2))

people (1) % weight = 1
people (1) % length = 1.0
people (2) % weight = 2
people (2) % length = 2.0

call my_sum ( people (:) % weight, answer % weight )
write (*, *)  answer % weight

call my_sum ( people (:) % length, answer % length )
write (*, *)  answer % length

end program test_dt
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!