将泛型过程作为实际参数传递给函数

mil*_*cic 8 fortran

我试图将泛型过程作为函数的实际参数传递:

module mymod
implicit none

interface func
  module procedure :: func1
  module procedure :: func2
endinterface func

contains

real function func1(x)
  real,intent(in) :: x
  func1 = 2*x
endfunction func1

real function func2(x,y)
  real,intent(in) :: x
  real,intent(in) :: y
  func2 = 2*x + 3*y
endfunction func2

real function func3(func,x,y)
  interface
    real function func(x,y)
      real,intent(in) :: x
      real,intent(in) :: y
    endfunction func
  endinterface
  real,intent(in) :: x
  real,intent(in) :: y
  func3 = func(x,y)
endfunction func3

endmodule mymod

program myprogram
use mymod
implicit none
write(*,*)func3(func,2.,3.)
endprogram myprogram
Run Code Online (Sandbox Code Playgroud)

gfortran 6.2.0注意到我不能这样做:

test.f90:43:16:

 write(*,*)func3(func,2.,3.)
                1
Error: GENERIC procedure ‘func’ is not allowed as an actual argument at (1)
Run Code Online (Sandbox Code Playgroud)

同样,使用ifort 17:

test.f90(39): error #8164: A generic interface name shall not be used as an actual argument.   [FUNC]
write(*,*)func3(func,2.,3.)
----------------^
test.f90(39): error #6637: When a dummy argument is a function, the corresponding actual argument must also be a function.   [FUNC]
write(*,*)func3(func,2.,3.)
----------------^
compilation aborted for test.f90 (code 1)
Run Code Online (Sandbox Code Playgroud)

我正在阅读关于通用接口的2008标准部分,我找不到这样的限制.我也想不出编译器无法在编译时解析通用接口的原因.我的直觉告诉我这应该是可行的,但我可能没有正确的方法.你知道一种符合标准的方法吗?

Vla*_*r F 7

不,这是不允许的.实际上,您甚至无法将通用INTRINSIC函数作为伪参数传递.

符合标准的方法是直接使用正确的特定功能.使用INTRINSIC函数时,有时必须为正确的类型编写包装器,具体时没有标准名称.

例如:

  call integrate(derf,0.,1.)

  contains
    function derf(x)
      real(dbl) :: derf
      real(dbl), intent(in) :: x
      derf = erf(x)
    end function
  end
Run Code Online (Sandbox Code Playgroud)

如果你想传递双精度真实(或任何其他)版本是必要的,erf()因为没有特定的功能可用.

  • 我将评论使用特定函数将在Fortran 2015中变为非标准.此时,将无法将内部函数作为过程参数传递,并且必须使用包装器方法来保持标准兼容.(我还注意到自Fortran 95以来没有添加内在函数的新特定名称.) (7认同)