fortranderived-typesfortran2003

Parametrized derived types with kind parameter as subroutine argument


Say we have the following code:

module foo
use :: iso_fortran_env
implicit none

type :: bar (p, q)
    integer, kind :: p
    integer, len  :: q
    integer(kind = p), dimension(q) :: x
end type bar

contains

subroutine barsub (this)
    class(bar(*,*)), intent(in) :: this
    write (*,*) this%x
end subroutine barsub

end module foo

This code does not compile with either gfortran 8 or pgfort 18.4. The pgi compiler says

Illegal selector - KIND value must be non-negative Assumed type parameter (*) cannot be used with non-length type parameter p

whereas gfortran yields

The KIND parameter 'p' at (1) cannot either be ASSUMED or DEFERRED

If I change above code to

subroutine barsub (this)
    class(bar(INT32,*)), intent(in) :: this
    write (*,*) this%x
end subroutine barsub

it compiles fine with both compilers.

Is it possible to write a subroutine where the kind parameter does not need to be specified explicitly? In the example above, the code would be the same for INT32, INT64, ... and I don't want to copy paste it for every imaginable value of the kind parameter. It works fine for the len parameter. Why can't I do the same with the kind parameter?


Solution

  • Is it possible to write a subroutine where the kind parameter does not need to be specified explicitly?

    No, kind type parameters need to be given by a constant expression or defaulted, see, e.g., the Fortran 2008 standard, definition 1.3.147.12.3.

    Why can't I do the same with the kind parameter?

    The fact that len and kind type parameters have different uses and requirements is the point of having two types of type parameters, if their characteristics were the same we wouldn't need two of them.

    Note that procedures require of the kind parameters of their dummy arguments of parameterized derived types just same they require of the kinds of their dummy arguments of intrinsic types: to have their values defined at compilation time.