我試圖編寫一個例程,該例程能夠將字符串轉換爲基於無限多態性的不同種類的數據類型。這個想法是用戶調用這個例程,在想要存儲數據的地方傳遞變量,並根據變量/參數類型定義轉換。將可分配字符傳遞給Fortran中具有無限多態僞參數的子例程
這個程序的摘錄是在這裏:
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
「此%F值」 是一個 「字符(LEN = :),分配」 的字符串。 當我嘗試使用這個程序傳遞一個分配的字符串,它的出口成功,沒有錯誤/異常提高:
character(len=:), allocatable :: value
call keyword%GetAsScalar(value)
但字符串「值」始終是空的。 即使在例程內部,在賦值「value = this%fValue」之後,值爲空(len(value)爲0)。
似乎編譯器無法檢測到參數的類型是字符(len = :),allocatable,因此無法將值分配給它。
當然,我有一些選擇,但能夠使用單一的rountine和沒有可選參數爲不同類型的數據的想法是非常好的。例如,我可以使用我創建的用戶定義類型來處理字符串。
但是我想知道這是否是Fortran 2008中的默認行爲。 而且,如果有辦法實現這一點,使用此例程以及一個「類(*)」虛擬結論,以轉換不同的類型,包括引用的可分配字符。例如,有一種方法可以強制例程內的分配?
我會感謝您的意見。 乾杯, 愛德華
感謝您的解釋@IanH。我將添加使用我創建的派生類型(字符串)的可能性,但將保留使用該字符串的可能性,並且必須在作爲參數傳遞給例程之前分配該觀察值。 – Jauch