假设我有这个简单的类:
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”,以便每次将此类型传递给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
答案 0 :(得分:2)
您需要具有通用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
值得注意的是,您需要一个实现此功能的编译器!