Question

I hope this is not a too stupid question, but is it possible to have functions or subroutines where I can pass the type of an array like

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

*Do something with array* 
end subroutine

or do I have to write a subroutine for each possible arr_type (e.g. integer, double precision,...) and overload the subroutine with an interface ?

Was it helpful?

Solution 2

You could experiment with Fortran 2003's unlimited polymorphism. Write your subroutine a bit like this:

subroutine foo(array)
implicit none
class(*), dimension(:) :: array

! Do something with array

end subroutine

From the point of view of abbreviating code this won't save you much because you're likely to have to write something like

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

But you may end up writing as many lines as if you follow Alexander Vogt's entirely sensible approach.

EDIT, after comments

What this approach won't deliver, because Fortran doesn't include its intrinsic types in any sort of type hierarchy, is a code such as

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

That would be useful, but I don't see it happening soon.

OTHER TIPS

Yes and no... You can bundle several functions/subroutines with different dummy arguments using an interface:

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

I know of no (simple) possibility to pass arrays with arbitrary basic type. You could take a look at transfer - but there be dragons ;-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top