Function 将类型绑定过程作为参数传递
我试图将类型绑定过程作为参数传递给另一个子例程。我想知道这在Fortran中是否可行。下面是一个代码片段,它显示了我正在尝试做的事情Function 将类型绑定过程作为参数传递,function,fortran,user-defined-types,fortran2003,Function,Fortran,User Defined Types,Fortran2003,我试图将类型绑定过程作为参数传递给另一个子例程。我想知道这在Fortran中是否可行。下面是一个代码片段,它显示了我正在尝试做的事情 module type_definitions type test_type integer :: i1, i2,i3 contains procedure :: add_integers_up end type test_type contains subroutine add_integers_up(this,i4,ans)
module type_definitions
type test_type
integer :: i1, i2,i3
contains
procedure :: add_integers_up
end type test_type
contains
subroutine add_integers_up(this,i4,ans)
class(test_type) :: this
integer :: i4,ans
ans = this%i1+this%i2+this%i3+i4
end subroutine add_integers_up
subroutine print_result_of_subroutine(i4,random_subroutine)
integer :: i4,ans
interface
subroutine random_subroutine(i1,i2)
integer:: i1,i2
end subroutine random_subroutine
end interface
call random_subroutine(i4,ans)
write(*,*) ans
end subroutine print_result_of_subroutine
end module type_definitions
program main
use type_definitions
implicit none
integer :: i1,i2,i3,i4
integer :: ans
type(test_type) :: test_obj
i1 =1; i2=2; i3=3
test_obj%i1 = i1
test_obj%i2 = i2
test_obj%i3 = i3
i4 = 4
call print_result_of_subroutine(i4,test_obj%add_integers_up)
end program main
这可以用Fortran实现吗?当我尝试使用ifort编译这段代码时,我遇到了一个编译器错误 您没有向我们显示您得到的确切错误消息,我也没有亲自尝试您的示例,但我很确定问题在于过程伪参数的接口与传递给它的实际参数的接口不对应
更明确地说,
random_子例程
声明为接受两个参数,而test_obj%add_integers_up
接受三个参数;即使其中一个函数用作传递的对象伪参数,它仍然算作该过程接口的一部分。test\u obj%add\u integers\u up不是一个过程-它是一个绑定,恰好是一个名为add\u integers\u up的过程。不能将绑定作为实际参数传递
如果要传递绑定关联的特定过程,请传递该过程!假设:
call print_result_of_subroutine(i4, add_integers_up)
但正如其他海报所指出的,在示例代码中,该过程的接口与子例程的print_result_中相应伪参数的接口不匹配
如果test_obj%add_integers_up引用了一个关联的过程指针组件(并且该组件的接口与_子例程的print_result_所期望的匹配),那么事情将按照您所期望的那样进行
请注意,Fortran 90不支持类型绑定过程(或过程指针组件)-您的代码非常需要Fortran 2003。没错!我只能补充说,我将在接口块中使用“过程”或“模块过程”,并避免直接指定接口。