簡體   English   中英

在Fortran中調用類型綁定的過程類型的數組綁定過程

[英]Calling type-bound procedure for an array of derrived types in Fortran

讓我們假設我有一個派生類型Coordinates與其類型綁定過程swap

module myTypes
    implicit none
    public :: Coordinates  

    type Coordinates
        real :: x,y
    contains
        procedure :: swap  ! Error here
    end type
contains
    subroutine swap(this)
        class (Coordinates) :: this
        this%x = this%x + this%y
        this%y = -(this%y - this%x)
        this%x = this%x - this%y
    end subroutine
end module

現在,如果我有一個名為point_ACoordinates實例,並且如果我想為它調用類型綁定過程swap ,我只會寫: call point_A%swap 但是,如果我有一組Coordinates實例,例如:

type(Coordinates), dimension(:), allocatable :: setOfPoints

然后為setOfPoints所有元素調用swap ,我想寫:

call setOfPoints(:)%swap

為了實現這一點,我將swap過程的代碼更改為:

subroutine swap(these)
        class (Coordinates), dimension(:)  :: these
        integer :: i
        do i = 1, size(this)
            this(i)%x = this(i)%x + this(i)%y
            this(i)%y = -(this(i)%y - this(i)%x)
            this(i)%x = this(i)%x - this(i)%y
        end do
end subroutine

不幸的是,gfortran並不喜歡我的想法。 在我在第一段代碼中標記的行上,它說:

Error: Passed-object dummy argument of 'swap' must be scalar.

問題:如何一次為派生類型的所有實例調用類型綁定過程? 我不想把調用放在循環中,但我想在之前編寫它,就像我們在Fortran中使用數組一樣。

我讀到了ELEMENTAL關鍵字,但如果我想使用它,我需要類型綁定過程為'純',這不是我的情況。 我嘗試在單詞procedure之后放置一個DEFERRED關鍵字,但編譯器說:

Error: Interface must be specified for DEFERRED binding

我為swap創建了一個接口,但我無法弄清楚它的放置位置。 我嘗試了很多位置,編譯器說'界面出乎意料'。 另外,我讀到了有關SELECT TYPE ,但我認為這對我的情況沒有幫助。

你的具體例子與ELEMENTAL完全沒問題

module myTypes
    implicit none
    public :: Coordinates  

    type Coordinates
        real :: x,y
    contains
        procedure :: swap  ! Error here
    end type
contains
    elemental subroutine swap(this)
        class (Coordinates), intent(inout) :: this
        this%x = this%x + this%y
        this%y = -(this%y - this%x)
        this%x = this%x - this%y
    end subroutine

end module

 use myTypes

 type(Coordinates) :: arr(10)

 arr = Coordinates(1.,2.)

 call arr%swap

 end

你的子程序是純粹的。 如果不能,請考慮使用impure elemental

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM