fortran66のブログ

fortran について書きます。

pointer 型の type-bound procedure なら sequence 並びな派生型でも pass 属性で呼び出せる

sequence 並びの派生型データ

昨日、procedure pointer を派生型の要素として持つ場合、その procedure が pass 属性で OO 風に呼び出せることを書きました。
fortran66.hatenablog.com

本来の contains で type-bound procedure を静的に与える場合、pass される第一引数の型が、extension 可能な class 属性を強制されます。したがって、データ並びが sequence 並びの時(padding や並べ替えを許さず宣言のママの並びを強制する )や bind(c) 型の場合(C 言語との互換性を持った padding は許す並び)は、それが許されていないので type-bound な procedure を与えられません。

ところが、procedure pointer で type-bound な procedure を与える場合は、pass される第一引数を type 属性で呼べるので、この制限が外れます。

以下実行例

ソース・プログラム

    module m_mod
      implicit none
      type :: t_type
        sequence 
        integer :: i, j
        procedure(p_f), pointer :: fun => f
     ! contains
     !   procedure :: fun => f ! syntax error
      end type t_type    
      abstract interface
        integer function p_f(this)
          import
          type(t_type), intent(in) :: this
        end function p_f
      end interface
    contains
      integer function f(this)
        type(t_type), intent(in) :: this
        f = this%i + this%j
      end function f
    end module m_mod
    
    program test
      use m_mod
      implicit none
      type (t_type) :: a
      !a = t_type(1, 2, f)
      a%i = 1
      a%j = 2
      print *, a%fun()
    end program test

実行例

           3
続行するには何かキーを押してください . . .