Can someone explain how I might access type bound subroutines across multiple instances of a type without iterating over each instance? In the code below, I have an allocatable 2d array (i.e., 'grid') of instances of the 'cell' type, which has variable var1. I can easily access var1 across all instances of the grid (e.g., grid%var1) returns an array of var1 values across the grid. However, I cannot call a type bound subroutine (called 'compute') unless I iterate over every instance of cell and call individually. Is there any way that this can be done without iterating over the grid?
module cellmodule
implicit none
type :: cell
real :: var1 = 0
contains
procedure, public :: compute
end type
Contains
subroutine compute(this)
class(cell) :: this
this%var1 = this%var1 + 1
end subroutine compute
end module cellmodule
module modelmodule
use cellmodule
type :: model
type(cell), allocatable, dimension(:,:) :: grid
end type
end module modelmodule
program testprogram
use cellmodule
use modelmodule
implicit none
integer :: x = 2
integer :: y = 2
Integer :: i, j
type(model) :: m
allocate(m%grid(x,y))
!I can access var1 across all instances of the cell type like
print*, m%grid%var1
m%grid%var1 = m%grid%var1 + 1.0
print*, m%grid%var1
!I can also iterate over the grid and call compute for each cell
do i = 1, x
do j = 1, y
call m%grid(i,j)%compute
End do
End do
print*, m%grid%var1
!HOWEVER, I can't do this:
call m%grid%compute
print*, m%grid%var1
end program
You have to declare the subroutine as elemental
(which in turn requires intent()
to be specified for the arguments.
elemental subroutine compute(this)
class(cell), intent(inout) :: this
this%var1 = this%var1 + 1
end subroutine compute