2013-07-03 46 views
3

假設我有這個簡單的類的類型綁定寫語句輸出:如何實現在Fortran派生型或

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 

我如何定義它的界面來「寫」,讓每一次這個type傳遞給write語句,它輸出由類方法writetype定義的字符串。

換句話說,用python的說法,我可以實現__str __()方法的等價物嗎?

我發現了誘人的花絮,暗示這是可能的,請參閱User-defined derived-type Input/Output procedures (Fortran 2003)User-defined derived-type Input/Output procedure interfaces (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 

回答

1

你需要有一個通用的WRITE(格式化的)結合,結合到具有適當特性的具體步驟。有關更多信息,請參閱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 

這可能也值得注意的是,你需要一個編譯器來實現這個!

+0

謝謝你,正是我所追求的! –

相關問題