Associated Pass Type Procedures as Arguments

I am trying to pass a type binding procedure as an argument to another routine. I want to know if this is possible in Fortran. Here is a snippet of code that shows what I'm trying to do.

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 

Can this be done in Fortran? I get a compiler error when I try to compile this code using ifort.

+3
source share
2 answers

test_obj% add_integers_up is not a procedure - it is a binding that happens with a procedure called add_integers_up. You cannot pass a binding as an actual argument.

If you want to pass the specific procedure that the binding is associated with, follow the procedure! Hypothetically:

 call print_result_of_subroutine(i4, add_integers_up) 

But, as other posters noted, in your sample code, the interface of this procedure does not match the interface of the corresponding dummy argument in print_result_of_subroutine.

If test_obj% add_integers_up refers to the associated component of the procedure pointer (and the interface for this component matches the expected print_result_of_subroutine), then everything will work as you expect.

Please note that Fortran 90 does not support type binding procedures (or components of a procedure pointer) - Fortran 2003 is very necessary for your code.

+5
source

You did not give us the exact error message, and I myself have not tried your example, but I am sure that the problem is that the interface of the argument of the fictitious procedure does not match the interface of the actual argument that is passed to it.

More explicitly, random_subroutine declared to take two arguments, and test_obj%add_integers_up takes three arguments; although one of them functions as an argument to the dummy object of the passed object, it is still considered part of the interface of this procedure.

+3
source

Source: https://habr.com/ru/post/1246995/


All Articles