Function 过程指针无法指向基本函数
我试图使用过程指针(Fortran 2003中的新功能)指向一个基本函数,但它不起作用。我真的需要函数是Function 过程指针无法指向基本函数,function,pointers,fortran,procedure,Function,Pointers,Fortran,Procedure,我试图使用过程指针(Fortran 2003中的新功能)指向一个基本函数,但它不起作用。我真的需要函数是ELEMENTAL,并且需要指向它的指针。在Fortran中,指向基本函数真的是不可能的吗 module elemfunc implicit none contains elemental function fun111(x) result(y) real*8, intent(in) :: x real*8 :: y
ELEMENTAL
,并且需要指向它的指针。在Fortran中,指向基本函数真的是不可能的吗
module elemfunc
implicit none
contains
elemental function fun111(x) result(y)
real*8, intent(in) :: x
real*8 :: y
y = x**2+1
end function fun111
end module elemfunc
program testptr
use elemfunc
implicit none
interface
elemental function func (z)
real*8 :: func
real*8, intent (in) :: z
end function func
end interface
procedure (func), pointer :: ptr
ptr => fun111
print *, ptr( (/1.0d0,2.0d0/) )
end program testptr
错误消息:
main.f90:12.7:ptr=>fun111
1
Nonintrinstic elemental procedure pointer 'func111' is invalid in procedure pointer assignment at (1)
在fortran 2003标准第7.4.2段“指针分配”中,明确规定不允许:
C728 (R742) The proc-target shall not be a nonintrinsic elemental procedure
(这个限制在fortran 2008标准中仍然存在,因此没有被放松。)我也有同样的问题,直到我使用gfortran编译时才意识到这是一个问题。不幸的是,还禁止将伪过程参数用于基本过程。然而,仍然可以实现您想要的功能,尽管这有点困难 你可以合法地让一个基本函数调用一个纯函数。根据您的需要,元素函数可以是类型绑定的,也可以不是类型绑定的 选择一 将过程指针和函数放入模块中:
module A
implicit none
procedure(func_IF), pointer :: ptr => null()
abstract interface
pure function func_IF(x)
real, intent(in) :: x
real :: func_IF
end function
end interface
contains
! Non type bound elemental
elemental function myfun1(x) result(r)
real, intent(in) :: x
real :: r
if(associated(ptr)) r = ptr(x)
end function
end module
选择二
将指针和函数放在派生类型中:
module B
implicit none
type :: foo
procedure(func_IF), nopass, pointer :: ptr => null()
contains
procedure, pass :: myfun2
end type
abstract interface
pure function func_IF(x)
real, intent(in) :: x
real :: func_IF
end function
end interface
contains
! Type bound elemental
elemental function myfun2(this, x) result(r)
class(foo), intent(in) :: this
real, intent(in) :: x
real :: r
if(associated(this%ptr)) r = this%ptr(x)
end function
end module
小型测试程序:
program main
use A
use B
implicit none
type(foo) :: myfoo
myfoo%ptr => bar
ptr => bar
print*, myfun1([10., 20.])
print*, myfoo%myfun2([10., 20.])
contains
! Demo pure function with interface func_IF
pure function bar(x)
real, intent(in) :: x
real :: bar
bar = x**2
end function
end
FWIW您的代码(显然)为我正确编译和执行。我使用的是英特尔Fortran 13.1.0.149。即使我最多检查11次警告和语法,编译器也不会发出任何抱怨。我不能肯定你的代码符合标准,但我看不出它也不符合标准。太棒了!我正在使用gfortran 4.7(不确定…)。也许我应该更新我的gfortran???@High Performance Mark看,seach‘elemental’,第一个匹配结果说elemental接口是不允许的,但我不知道它是否与elemental函数相同……最新的gfortran 4.8产生了相同的约束。是的,这与OP在评论中引用的约束相同。@VladimirF:Ah,我没有看那个。看来OP已经知道他的问题的答案了。谢谢大家。这个限制真的让我很难过!。。。。我必须重新编写代码,而不使用基本函数