Search code examples
variablesfortransubroutine

Arbitray variable/array type in fortran functions/subroutines


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 ?


Solution

  • 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.