4

この単純なクラスがあるとします:

   Module Foo
        ...
        character(len=3), parameter :: describe_Foo=(/'BAR', 'BED', 'BOD'/)
        ...
        type :: A
            real :: value
            integer :: descriptor
        contains
            procedure :: getter
            procedure :: setter
            ...
        end type A

   contains
        function writetype(self,...)
            ...
            write(writetype,*) self%value, describe_foo(self%descriptor)
        end function writetype
   ...
   end module Foo

このタイプが write ステートメントに渡されるたびに、クラスメソッドで定義された文字列を出力するように、そのインターフェイスを「書き込み」に定義するにはどうすればよいですかwritetype

つまり、Python の用語では、__str__()メソッドに相当するものを実装できますか?

これが可能であることを示唆する興味深い情報を見つけました。ユーザー定義の派生型入力/出力プロシージャー (Fortran 2003)およびユーザー定義の派生型入力/出力プロシージャー インターフェイス (Fortran 2003)を参照してください。これらのドキュメントは、必要なメソッドを記述するための十分な情報を提供しますが、必要な動作が発生するようにインターフェイスまたはプロシージャの仕様を定義する方法はまだ不明です。

適用例:

program test
    ...
    type(A) :: bartype, bedtype
    ...
    bartype=A(120.0,1)
    bedtype=A(102.0,2)
    write(*,*) bartype,bedtype
end program test

望ましい出力:

>test.exe
 120.0000 BAR
 102.0000 BED
4

1 に答える 1

3

適切な特性を持つ特定のプロシージャにバインドされた汎用 WRITE(FORMATTED) バインドが必要です。詳細については、F2008 標準のセクション 9.6.4.8 を参照してください。

type :: A
  real :: value
  integer :: descriptor
contains
  procedure :: writetype
  generic :: write(formatted) => writetype
end type A
...
subroutine writetype(dtv, unit, iotype, v_list, iostat, iomsg)
  ! Argument names here from the std, but you can name them differently.
  class(A), intent(in) :: dtv         ! Object to write.
  integer, intent(in) :: unit         ! Internal unit to write to.
  character(*), intent(in) :: iotype  ! LISTDIRECTED or DTxxx
  integer, intent(in) :: v_list(:)    ! parameters from fmt spec.
  integer, intent(out) :: iostat      ! non zero on error, etc.
  character(*), intent(inout) :: iomsg  ! define if iostat non zero.
  ...
  write (unit, "(F9.4,1X,A)", IOSTAT=iostat, IOMSG=iomsg)  &
      dtv%value, describe_foo(dtv%descriptor)
end subroutine writetype

これを実装するコンパイラが必要であることも、おそらく注目に値するでしょう!

于 2013-07-03T23:49:14.910 に答える