Persistent array of function pointers in Fortran 2003

Dear Fortran Programmers,

Does anyone know if it is possible to declare an array of constant (parameter) procedure pointers in Fortran 2003 or higher?

As indicated below, I have a switch function that calls different functions depending on the input integer argument. It uses an array of procedure pointers (wrapped in derivatives). This array must be initialized with a procedure init()at runtime before it can be used. Is there any way to initialize this array already at compile time and avoid the need for such initialization? It can also be defined as parameter, since at startup the value will not change.

module testmod
  implicit none

  interface
    function funcInterface() result(res)
      integer :: res
    end function funcInterface
  end interface

  type :: ptrWrap
    procedure(funcInterface), nopass, pointer :: ptr
  end type ptrWrap

  type(ptrWrap) :: switcher(2)

contains

  subroutine init()
    switcher(1)%ptr => func1
    switcher(2)%ptr => func2
  end subroutine init

  function callFunc(ii) result(res)
    integer, intent(in) :: ii
    integer :: res
    res = switcher(ii)%ptr()
  end function callFunc

  function func1() result(res)
    integer :: res
    res = 1
  end function func1

  function func2() result(res)
    integer :: res
    res = 2
  end function func2

end module testmod


program test
  use testmod
  implicit none

  call init()  ! I'd like to get rid of this call.
  print *, callFunc(1)
  print *, callFunc(2)

end program test
+4
2

Fortran 2008 ( NULL()). .

! In the scope of the module.
...
type(ptrWrap), parameter :: switcher(2) = [ptrWrap(func1), ptrWrap(func2)]
...
+2

, . 2008 parameter data object, .

, ?

+2

All Articles