如何在 Fortran 中指向 class 方法?

How to point to a class method in fortran?

我有一个模块,它定义了一个 class 具有一些属性和一个方法 (proc1),它是一个函数。另一个模块定义了一个函数 (proc2),它使用一个参数评估函数,给定一个指向该函数和参数的指针。在主程序中,我想定义一个函数指针 (fun),它指向 class' 方法 (proc1),这样计算 fun(x) 就等同于评估 obj1 % proc1(x)。那可能吗?

我的编译器 gfortran 7.3 抱怨

Expected argument list at (1)

使用以下语法。

module objmod
   implicit none
   ! object with some data and a method
   type obj 
      real                  :: a, b, c
   contains
      procedure, pass(self) :: proc1
   end type obj

contains
   ! method which uses object and a variable
   pure real function proc1(self, var) 
      class(obj), intent(in) :: self
      real, intent(in)       :: var
      proc1 = var * (self % a + self % b + self % c)
   end function proc1

end module objmod

module funmod
   implicit none

contains
   ! function that evaluates fun(a), or does more complicated stuff
   real function proc2(funptr, a)
      procedure(real), pointer :: funptr
      real, intent(in)         :: a
      proc2 = funptr(a)
   end function proc2

end module funmod

program funPtr

   use objmod
   use funmod

   implicit none

   type(obj)                :: obj1
   real                     :: a, x
   procedure(real), pointer :: fun

   obj1 % a =  1.0
   obj1 % b =  2.0
   obj1 % c =  3.0
   a        = -1.5
   fun => obj1 % proc1 ! function pointer to fun(x) = proc1(obj1, x)

   x = proc2(fun, a)

   print *, x
end program funPtr

不,你不能这样做。标准说,对于指针赋值的过程目标:

C1030 (R1040) A procedure-name shall be the name of an internal, module, or dummy procedure, a procedure pointer, a specific intrinsic function listed in Table 16.2, or an external procedure that is accessed by use or host association, referenced in the scoping unit as a procedure, or that has the EXTERNAL attribute.

在您的示例中,obj1%proc1 是其中的 none。如果您给 fun 一个显式接口,您可以将指针分配给 proc1(即实际过程而不是类型组件)。当然,如果你这样做,你会失去传递的对象方面。

问题是函数指针没有类型绑定过程的上下文。