gpt4 book ai didi

fortran - 除了选择类型子句之外,是否有更清晰的方式来表达派生类型?

转载 作者:行者123 更新时间:2023-12-03 23:45:08 25 4
gpt4 key购买 nike

在下面的代码中,我使用派生类型函数来拥有一个通用的 api,用于从当前对象生成新的派生类型。我意识到编译器无法从分配语句中获取类型信息,因为对象也可以作为其他东西被释放和重新分配,但我很好奇是否有一种更干净的方法来将分配的对象作为正确的派生类型而不是选择类型语句。关于它的一些东西只是感觉很有趣,因为在函数中我绝对知道它的类型是什么,即使编译器没有

module poly

implicit none

type, abstract :: parent
contains
procedure(i_new_child), deferred, pass(this) :: new_child
end type parent

interface
function i_new_child(this) result(child)
import
class(parent), intent(in) :: this
class(parent), allocatable :: child
end function i_new_child
end interface

type, extends(parent) :: child1
integer :: a
contains
procedure, pass(this) :: new_child => new_child1
end type child1

contains

function new_child1(this) result(child)
class(child1), intent(in) :: this
class(parent), allocatable :: child
allocate(child1 :: child)
! child%a = 1 ! 'a' at (1) is not a member of the 'parent' structure
select type (child)
class is (child1)
child%a = 1
end select
end function new_child1

end module poly

最佳答案

在需要“复杂”构造的情况下,分配一个具体类型的变量,然后将该变量 MOVE_ALLOC 传递到结果。

function new_child1(this) result(child)
class(child1), intent(in) :: this
class(parent), allocatable :: child
type(child1), allocatable :: tmp

allocate(tmp)
tmp%a = 1
! Real world complex construction goes here.
! Once construction of tmp is complete:
call move_alloc(tmp, child)
end function new_child1
对于琐碎/简单的构造,将结构构造函数与分配给多态变量时的自动分配结合使用。
function new_child1(this) result(child)
class(child1), intent(in) :: this
class(parent), allocatable :: child

child = child1(a=1)
end function new_child1

关于fortran - 除了选择类型子句之外,是否有更清晰的方式来表达派生类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63252903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com