roy*_*vib 6 arrays fortran heterogeneous
我正在尝试创建包含不同类型变量的异构数组,例如[ 1.0, 7, "hi" ].我试图包含class(*)或type(*)在数组构造函数中(请参阅下面代码的结尾),但gfortran5.2只是将其视为语法错误.有没有办法用数组构造函数创建这样的数组,还是有必要使用不同的方法(例如,定义一个单独包含每个元素的类型)?
更多细节:
以下代码是我想创建这样一个数组的一个例子.该checktype_multi例程接收多个参数与所述optional关键字,但由于固定数量的参数的这种方法显然是有限的.为了允许任意数量的参数,我尝试了checktype_array例程,但似乎不可能传递具有不同类型的数组......更实际的情况可能是创建一个子例程来打印具有各种类型的可变数量的参数.
module mymod
implicit none
contains
subroutine checktype ( x )
class(*) :: x
select type ( x )
type is ( integer ) ; print *, "int : ", x
type is ( real ) ; print *, "real : ", x
type is ( character(*) ) ; print *, "string : ", x
endselect
end subroutine
subroutine checktype_multi ( x1, x2, x3 )
class(*), optional :: x1, x2, x3
print *
if ( present( x1 ) ) call checktype ( x1 )
if ( present( x2 ) ) call checktype ( x2 )
if ( present( x3 ) ) call checktype ( x3 )
end subroutine
subroutine checktype_array ( a )
class(*) :: a(:)
integer :: k
print *
do k = 1, size( a )
call checktype ( a( k ) )
enddo
end subroutine
end module
program main
use mymod
call checktype_multi ( 1.0 )
call checktype_multi ( 1.0, 7 )
call checktype_multi ( 1.0, 7, "hi" )
! call checktype_array ( [ 1.0, 7, "hi" ] ) !! error (this is to be expected)
!>>> Here is the problem.
! call checktype_array ( [ type(*) :: 1.0, 7, "hi" ] ) !! this is also an error
! call checktype_array ( [ class(*) :: 1.0, 7, "hi" ] ) !! this too
end program
Run Code Online (Sandbox Code Playgroud)
数组的元素可能仅在值上彼此不同.它们的类型或任何其他属性不同.
相反,在无限多态可分配组件周围使用派生类型包装器.然后,组件的动态类型被视为包装器类型的对象的值的一部分.
TYPE :: wrapper
CLASS(*), ALLOCATABLE :: item
END TYPE wrapper
CALL sub([wrapper(1), wrapper(2.0), wrapper('3')])
Run Code Online (Sandbox Code Playgroud)
(数组构造函数(或结构构造函数)指定一个值.值本身不能是多态的,值的类型总是只是值的类型.数组构造函数中可选的前导类型规范的语法反映了这一点,它只是一个类型规范,而不是声明类型规范.)