1

我需要实现一个函数,它将序列化(即保存到未格式化的二进制文件)一个包含对象数组的类,这些对象属于同一个抽象类,但属于几个不同的继承类。

关键是,这个数组被传递给我的函数,它是由用户的操作创建的。因此,我无法知道存储在数组中的特定类型。

有没有办法以某种方式实现写入和读取 I/O 方法,它可以自动写入数组而无需指定其单个元素的类型?

我写了这段代码来说明我的情况:

module m
    implicit none

    type :: container
        class(a), allocatable :: item
    end type container

    type, abstract :: a
        integer, public :: num
    contains
        procedure :: write_impl => write_a
        procedure :: read_impl => read_a

        generic            :: write(unformatted) => write_impl
        generic            :: read(unformatted)  => read_impl
    end type a

    type, extends(a) :: b
        integer, public :: num2
    contains
        procedure :: write_impl => write_b
        procedure :: read_impl => read_b
   end type b

    type, extends(a) :: c
    end type c

contains

    subroutine write_a(this, unit, iostat, iomsg)
        class(a), intent(in)    :: this
        integer, intent(in)         :: unit
        integer, intent(out)        :: iostat
        character(*), intent(inout) :: iomsg

        write(unit, iostat=iostat, iomsg=iomsg) this%num
    end subroutine write_a

    subroutine read_a(this, unit, iostat, iomsg)
        class(a), intent(inout) :: this
        integer, intent(in)         :: unit
        integer, intent(out)        :: iostat
        character(*), intent(inout) :: iomsg

        read(unit, iostat=iostat, iomsg=iomsg) this%num
    end subroutine read_a

    subroutine write_b(this, unit, iostat, iomsg)
        class(b), intent(in)    :: this
        integer, intent(in)         :: unit
        integer, intent(out)        :: iostat
        character(*), intent(inout) :: iomsg

        write(unit, iostat=iostat, iomsg=iomsg) this%num, this%num2
    end subroutine write_b

    subroutine read_b(this, unit, iostat, iomsg)
        class(b), intent(inout) :: this
        integer, intent(in)         :: unit
        integer, intent(out)        :: iostat
        character(*), intent(inout) :: iomsg

        read(unit, iostat=iostat, iomsg=iomsg) this%num, this%num2
    end subroutine read_b
end module m

program mwe
    use m

    implicit none

    class(a), allocatable :: o1, o2, o3
    class(container), allocatable :: arr(:)
    integer :: i

    o1 = b(1,2)
    o2 = c(3)

    allocate(arr(2))
    arr(1) = container(o1)
    arr(2) = container(o2)


    ! How to serialize 'arr' without specifying its elements' types?

end program mwe

那么,有什么办法,如何序列化这样的数组而无需手动指定,即o1类型bo2类型c

我需要能够序列化一个抽象类型的数组,a并且还可以在不了解其元素的情况下从二进制文件中读取它。

4

0 回答 0