2013-07-03 49 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

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

相关问题