如果您不愿意更改代码的结构,那么 bdforbes 提出的 SELECT CASE 方法是一种选择。
除此之外,您可以使用多态性并用不同类型替换数据类型组件,这些类型都是相同父类型的扩展。这就是类型绑定过程(类型定义中 contains 之后的过程语句)存在的根本原因,所以您不妨按预期使用它们!
type, public, abstract :: image
! Common components to all extensions
logical :: initialized = .false.
character(256) :: path = "" ! Path to image
integer :: dimensions(3) = -1 ! Dimensions of image
contains
procedure :: initialize
! Abstract interface pxvalues_image specified what the interface must
! look like. Deferred attribute means that extensions of image
! must specify a specific procedure for the pxvalues binding. All
! specific procedures must have the same interface bar the passed
! argument.
procedure(pxvalues_image), deferred :: pxvalues
procedure :: getMeta
end type image
abstract interface
subroutine pxvalues_image(obj, ...)
import :: image
class(image), intent(in) :: obj
...
end subroutine pxvalues_image
end interface
! A type for images that have integer2 data.
type, public, extends(image) :: image_integer2
contains
procedure :: pxvalues => pxvalues_integer2
end type image_integer2
! A type for images that have integer4 data.
type, public, extends(image) :: image_integer4
contains
procedure :: pxvalues => pxvalues_integer4
end type image_integer4
特定过程''pxvalues_integer2''、''pxvalues_integer4''等,然后采用扩展类型的初始参数。
而不是设置数据类型组件,创建初始“图像”对象的代码应该将对象创建为图像的适当扩展,也许:
subroutine create_image(object)
class(image), intent(out), allocatable :: object
...
! We want an image that for integer2's
allocate(image_integer2 :: object)
这种方法的含义需要比孤立的示例片段中提供的更多的代码知识。