Fortran procedure pointer to subroutines in derived type

前端 未结 2 1018
礼貌的吻别
礼貌的吻别 2020-12-28 11:08

In Fortran, I need a procedure pointer inside a derived type that can point to one of several subroutines. This problem seems to be common on SO:

Fortran save proced

2条回答
  •  Happy的楠姐
    2020-12-28 11:38

    Here's my working example:

    module obj_mod
        integer, parameter :: n = 5
    
        type obj_type
            procedure(sub_interface), pointer, nopass :: obj_sub => NULL()
        end type
    
        interface
            subroutine sub_interface(y, x)
                import n
                double precision, dimension(n) :: x, y
            end subroutine sub_interface
        end interface
    
    contains 
        subroutine sq_sub(x, y)
            double precision, dimension(n) :: x, y
            y = x ** 2
        end subroutine
    
        subroutine exp_sub(x, y)
            double precision, dimension(n) :: x, y
            y = exp(x)
        end subroutine
    
    end module 
    
    program member_subroutine
        use obj_mod
        type(obj_type) obj
        double precision, dimension(n) :: x, y
    
        x = (/ 1, 2, 3, 4, 5 /)
        write(*,*) 'x =', x
    
        obj%obj_sub => sq_sub
        call obj%obj_sub(x, y)
        write(*,*) 'y1 =', y
    
        obj%obj_sub => exp_sub
        call obj%obj_sub(x, y)
        write(*,*) 'y2 =', y
    end program member_subroutine
    

提交回复
热议问题