1

我正在尝试编写一个能够基于无限多态性将字符串转换为不同类型数据类型的例程。这个想法是用户调用这个例程,将变量传递到它想要存储数据的位置,以及基于变量/参数类型定义转换的例程。

此例程的摘录如下:

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(*)”虚拟参数来转换不同的类型,包括称为可分配字符。有一种方法可以在例程内部强制分配,例如?

我会很感激你的意见。干杯,爱德华多

4

1 回答 1

5

在选择类型(或关联)构造中,关联名称从不具有可分配属性 (16.5.1.6p2),无论选择是否具有该属性。

在您的情况下,选择器也缺少该属性 -value虚拟参数未声明为可分配的。不允许将未分配的实际参数与非可选的不可分配的虚拟参数相关联。除此之外,不允许在选择类型或关联构造中使用未分配的选择器。

您需要value在调用之前将实际参数分配给某个长度,value然后关联名称将在选择类型构造中具有该固定长度。或者,将可分配字符变量包装为派生类型中的组件。

于 2014-12-29T17:49:11.890 回答