传递类型绑定程序作为参数传递类型绑定程序作为参数(Passing type bound proced

2019-05-12 09:35发布

我想传递一个类型限定的过程作为参数传递给另一个子程序。 我想知道这是否可能用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)
       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编译这段代码。

Answer 1:

test_obj%add_integers_up不是一个程序 - 它是有约束力的,恰好是一个名为add_integers_up程序。 你可以不通过结合作为实际参数。

如果你想传递的结合与相关的具体程序,然后通过程序! 可以想像:

call print_result_of_subroutine(i4, add_integers_up)

但正如其他海报指出,在您的示例代码程序的接口不匹配print_result_of_subroutine相应的伪参数的接口。

如果test_obj%add_integers_up提到了相关的程序指针组件(和该组件的接口匹配由print_result_of_subroutine所预期发生了什么),那么,你似乎在期待的事情会工作。

需要注意的是Fortran 90的不支持类型绑定程序(或程序指针组件) - 你的代码非常需要2003 Fortran语言。



Answer 2:

你没告诉我们你得到了确切的错误信息,我没有尝试你的榜样,不过我敢肯定,问题是该程序的伪参数的接口不符合实际的接口传递给它的参数。

更明确地说, random_subroutine被声明为接受两个参数,而test_obj%add_integers_up有三个参数; 即使其中一人充当传递对象伪参数,它仍然被认为是程序接口的一部分。



文章来源: Passing type bound procedures as arguments