我正在编写一个库,用于将多种类型的几何(球体、平面、NURBS 曲面、stl 文件...)导入到科学的 Fortran 代码中。这种问题似乎是为 OOP 量身定做的,因为定义 atype :: geom
和 thentype,extends(geom) :: analytic
等很简单。我遇到问题的部分是文件 IO。
在这一点上,我的解决方案是编写定义形状的参数,包括一些告诉我它是哪种形状的标志。阅读时,我实例化了一个class(geom) :: object
, (因为我事先不知道它将是哪个子类型)但是我该如何阅读它呢?
我无法访问该子类型的任何特定组件。我读到向下转换是禁止的,此外,新的allocate(subtype :: class)
似乎不起作用。新的READ(FORMATTED)
似乎没有由 ifort 或 gfortran 实现。IE
module geom_mod
type :: geom
end type
type,extends(geom) :: sphere
integer :: type
real(8) :: center(3),radius
contains
generic :: READ(FORMATTED)=> read_sphere ! not implemented anywhere
end type
contains
subroutine read_geom(object)
class(geom),intent(out),pointer :: object
integer :: type
read(10,*) object%type ! can't access the subtype data yet
read(10,*) type
backspace(10)
if(type==1) then
allocate(sphere :: object)! downcast?
read(10,*) object ! doesn't work
end if
end read_geom
end module
我对这一切都错了吗?我可以使用多态性以外的东西来破解它,但这似乎在其他任何地方都更干净。协助将不胜感激。
编辑:使用 IanH 模块的示例程序
program test
use geom_mod
implicit none
class(geom),allocatable :: object
open(10)
write(10,*) '1'
write(10,*) sphere(center=0,radius=1)
rewind(10)
call read(object) ! works !
end program test