将通用过程作为实际参数传递给函数 [英] Passing a generic procedure to a function as actual argument

查看:186
本文介绍了将通用过程作为实际参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将通用过程作为实际参数传递给函数:

I am attempting to pass a generic procedure as an actual argument to a function:

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

gfortran 6.2.0指出我不能这样做:

gfortran 6.2.0 notes that I cannot do this:

test.f90:43:16:

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

类似地,使用ifort 17:

Similarly, with 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)

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

I am reading through the 2008 Standard section on generic interfaces and I cannot find such restriction. I also cannot think of a reason why the compiler would not be able to resolve the generic interface at compile-time. My gut is telling me that this should be doable, but I may not have the right approach. Do you know of a standard-compliant way to do this?

推荐答案

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

No, this is not allowed. Actually, you cannot even pass generic INTRINSIC functions as dummy arguments.

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

A standard compliant way is to use the right specific functions directly. With INTRINSIC functions you sometimes must write a wrapper for the right kind, when the specific doesn't have a standard name.

例如:

  call integrate(derf,0.,1.)

  contains
    function derf(x)
      real(dbl) :: derf
      real(dbl), intent(in) :: x
      derf = erf(x)
    end function
  end

如果要通过erf()的双精度实数(或任何其他)版本,则

是必需的,因为没有可用的特定功能.

is necessary if you want to pass the double precision real (or any other) version of erf() because there is no specific function available.

这篇关于将通用过程作为实际参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆