我正在尝试创建一个类型,它将作为任意其他类型的包装器,因此我可以创建一个异构数组,正如Fortran 类的异构数组和Fortran 中的创建异构数组中所建议的那样。
所以,我试着像这样实现它:
module m
implicit none
type :: container
class(*), pointer, public :: item
end type container
end module m
program mwe
use m
implicit none
type(container) :: cont
integer, target :: i
i = 5
cont = container(i)
write(*,*) cont%item
end program mwe
现在我收到错误
test4.f90(20): error #5513: A polymorphic I/O list item requires a user-defined derived-type input/output procedure.
write(*,*) cont%item
----^
compilation aborted for test4.f90 (code 1)
所以我尝试像这样实现 I/O:
module m
implicit none
type :: container
class(*), pointer, public :: item
contains
procedure :: write_sample => write_container_sample_impl
procedure :: read_sample => read_container_sample_impl
generic :: write(unformatted) => write_sample
generic :: read(unformatted) => read_sample
end type container
contains
subroutine write_container_sample_impl(this, unit, iostat, iomsg)
class(container), intent(in) :: this
integer, intent(in) :: unit
integer, intent(out) :: iostat
character(*), intent(inout) :: iomsg
write(unit, iostat=iostat, iomsg=iomsg) this%item
end subroutine write_container_sample_impl
subroutine read_container_sample_impl(this, unit, iostat, iomsg)
class(container), intent(inout) :: this
integer, intent(in) :: unit
integer, intent(out) :: iostat
character(*), intent(inout) :: iomsg
read(unit, iostat=iostat, iomsg=iomsg) this%item
end subroutine read_container_sample_impl
end module m
program mwe
use m
implicit none
type(container) :: cont
integer, target :: i
i = 5
cont = container(i)
write(*,*) cont%item
end program mwe
但即使在我的新方法中也会出现同样的错误:
test4.f90(22): error #5513: A polymorphic I/O list item requires a user-defined derived-type input/output procedure.
write(unit, iostat=iostat, iomsg=iomsg) this%item
--------^
test4.f90(31): error #5513: A polymorphic I/O list item requires a user-defined derived-type input/output procedure.
read(unit, iostat=iostat, iomsg=iomsg) this%item
--------^
test4.f90(47): error #5513: A polymorphic I/O list item requires a user-defined derived-type input/output procedure.
write(*,*) cont%item
----^
所以,我有两个问题:
- 我应该如何正确实施它?
- 将项目变量声明为指针还是可分配变量更好/更容易?