我正在尝试编写一个能够根据无限多态将字符串转换为不同类型的数据类型的例程。我们的想法是用户调用此例程,将变量传递到要存储数据的位置,并根据变量/参数类型定义转换例程。
此例程的摘录如下:
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
“此%fValue”是“字符(len = :),可分配”字符串。 当我尝试使用此例程传递可分配的字符串时,它会成功退出,不会出现错误/异常:
character(len=:), allocatable :: value
call keyword%GetAsScalar(value)
但字符串“value”始终为空。 即使在例程中,在赋值“value = this%fValue”之后,值为空(len(value)为0)。
似乎编译器无法检测到参数的类型为字符(len = :),可分配,等等,无法为其赋值。
当然我有一些选择,但是能够使用单个rountine并且没有可选参数用于不同类型的数据的想法非常好。
我可以使用我创建的用户定义类型来处理字符串,例如。
但我想知道这是否是Fortran 2008中的默认行为。 而且,如果有办法实现这一点,使用这个例程,使用单个“class(*)”虚拟argumment,转换不同的类型,包括引用的可分配字符。有一种方法可以在例程中强制分配,例如?
我将非常感谢您的评论。 干杯, 爱德华
答案 0 :(得分:4)
在选择类型(或关联)构造中,无论select是否具有该属性,关联名称 never 都具有可分配属性(16.5.1.6p2)。
在您的情况下,选择器也缺少该属性 - value
伪参数未声明为可分配。不允许将未分配的实际参数与非可选的不可分配的伪参数相关联。除此之外,您不允许在选择类型或关联构造中使用未分配的选择器。
您需要在调用之前将value
实际参数分配给某个长度,value
关联名称将在select类型构造中具有该固定长度。或者,将可分配字符变量包装为派生类型中的组件。