繁体   English   中英

如何使用名称列表以派生类型编写可分配数组?

[英]How to write an allocatable array in a derived type using namelists?

我在使用名称列表编写嵌套在派生类型中的可分配数组时遇到麻烦。 一个最小的例子如下所示。 我如何修改程序以使派生类型内部的可分配数组像未嵌套一样工作?

program test

    implicit none

    type struct_foo
        integer, allocatable :: nested_bar(:)
    end type struct_foo

    integer, allocatable :: bar(:)
    type(struct_foo) :: foo
    ! namelist / list / foo, bar
    namelist / list / bar

    allocate(bar(5))
    bar = [1:5]

    allocate(foo%nested_bar(5))
    foo%nested_bar=[1:5]

    write(*,list)

end program test

将foo从名称列表中注释掉,它可以正常工作,并产生输出:

 &LIST
 BAR     =           1,           2,           3,           4,           5
 /

包含foo时,程序无法编译:

>> ifort -traceback test_1.f90 -o test && ./test
test_1.f90(20): error #5498: Allocatable or pointer derived-type fields require a user-defined I/O procedure.
    write(*,list)
--------^
compilation aborted for test_1.f90 (code 1)

如错误消息所述,您需要提供一个用户定义的派生类型I / O(UDDTIO)过程。 对于具有可分配或指针组件的任何对象的输入/输出,这是必需的。

如何在文件中格式化派生类型的对象的格式完全在UDDTIO过程的控制之下。

下面是一个使用非常简单的输出格式的示例。 通常,实现名称列表输出的UDDTIO过程将使用与名称列表输出的其他方面一致的输出格式,并且通常还将存在一个相应的UDDTIO过程,该过程随后能够读回格式化的结果。

module foo_mod
  implicit none

  type struct_foo
    integer, allocatable :: nested_bar(:)
  contains
    procedure, private :: write_formatted
    generic :: write(formatted) => write_formatted
  end type struct_foo
contains
  subroutine write_formatted(dtv, unit, iotype, v_list, iostat, iomsg)
    class(struct_foo), intent(in) :: dtv
    integer, intent(in) :: unit
    character(*), intent(in) :: iotype
    integer, intent(in) :: v_list(:)
    integer, intent(out) :: iostat
    character(*), intent(inout) :: iomsg

    integer :: i

    if (allocated(dtv%nested_bar)) then
      write (unit, "(l1,i10,i10)", iostat=iostat, iomsg=iomsg)   &
          .true.,  &
          lbound(dtv%nested_bar, 1),  &
          ubound(dtv%nested_bar, 1)
      if (iostat /= 0) return
      do i = 1, size(dtv%nested_bar)
        write (unit, "(i10)", iostat=iostat, iomsg=iomsg)  &
            dtv%nested_bar(i)
        if (iostat /= 0) return
      end do
      write (unit, "(/)", iostat=iostat, iomsg=iomsg)
    else
      write (unit, "(l1,/)", iostat=iostat, iomsg=iomsg) .false.
    end if
  end subroutine write_formatted
end module foo_mod

program test
  use foo_mod

  implicit none

  integer, allocatable :: bar(:)
  type(struct_foo) :: foo
  namelist / list / foo, bar

  allocate(bar(5))
  bar = [1:5]

  allocate(foo%nested_bar(5))
  foo%nested_bar=[1:5]

  write (*,list)
end program test

UDDTIO的使用显然需要实现此Fortran 2003语言功能的编译器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM