我正在尝试编写一个能够基于无限多态性将字符串转换为不同类型数据类型的例程。这个想法是用户调用这个例程,将变量传递到它想要存储数据的位置,以及基于变量/参数类型定义转换的例程。
此例程的摘录如下:
subroutine GetAsScalar (this, value, status)
!Arguments-------------------------------------------------------------
class(TKeyword) :: this
class(*) :: value
logical, optional :: status
!Local-----------------------------------------------------------------
integer :: stat
!----------------------------------------------------------------------
stat = 0
select type (value)
type is (REAL(real32)) !single precision
read (this%fValue, *, IOSTAT = stat) value
type is (REAL(real64)) !double precision
read (this%fValue, *, IOSTAT = stat) value
type is (LOGICAL)
read (this%fValue, *, IOSTAT = stat) value
type is (INTEGER(int32)) !integer
read (this%fValue, *, IOSTAT = stat) value
type is (INTEGER(int64)) !long integer
read (this%fValue, *, IOSTAT = stat) value
type is (CHARACTER(*))
value = this%fValue
class default
this%Message = "Invalid data type"
status = .false.
return
end select
if (present (status)) then
if (stat /= 0) then
status = .false.
else
status = .true.
endif
endif
end subroutine GetAsScalar
“this%fValue”是一个“字符(len=:),可分配”字符串。当我尝试使用此例程传递可分配字符串时,它会成功退出,不会引发错误/异常:
character(len=:), allocatable :: value
call keyword%GetAsScalar(value)
但字符串“value”始终为空。即使在例程内部,在赋值“value = this%fValue”之后,value 也是空的(len(value) 为 0)。
似乎编译器无法检测到参数是字符类型(len=:)、可分配的,因此无法为其分配值。
当然,我有一些替代方案,但是能够使用单个例程并且没有可选参数来处理不同类型的数据的想法非常好。
例如,我可以使用我创建的用户定义类型来处理字符串。
但我想知道这是否是 Fortran 2008 中的默认行为。而且,如果有办法做到这一点,使用这个例程和一个“class(*)”虚拟参数来转换不同的类型,包括称为可分配字符。有一种方法可以在例程内部强制分配,例如?
我会很感激你的意见。干杯,爱德华多