在Fortran中将可分配字符传递给具有无限多态伪参数的子例程

Jau*_*uch 1 polymorphism fortran character subroutine fortran2003

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

该例程的摘录在这里:

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
Run Code Online (Sandbox Code Playgroud)

“ this%fValue”是“可分配的字符(len = :)”字符串。当我尝试使用此例程传递可分配的字符串时,它成功退出,没有错误/异常引发:

character(len=:), allocatable :: value
call keyword%GetAsScalar(value)
Run Code Online (Sandbox Code Playgroud)

但是字符串“ value”始终为空。即使在例程中,在分配“值= this%fValue”之后,值也为空(len(value)为0)。

似乎编译器无法检测到该参数的类型为character(len = :),可分配,因此无法为其分配值。

当然,我有一些替代方法,但是能够使用单个常规程序且不对其他类型的数据使用可选参数的想法确实很棒。

例如,我可以使用我创建的用户定义类型来处理字符串。

但是我想知道这是否是Fortran 2008中的默认行为。此外,是否有一种方法可以使用此例程,并使用单个“ class(*)”虚拟实数来转换包括指可分配的字符。有一种方法可以强制在例程中进行分配,例如?

感谢您的评论。干杯,爱德华多

Ian*_*anH 5

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

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

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