我正在尝试创建包含不同类型变量的异构数组,例如[ 1.0, 7, "hi" ]
. 我尝试在数组构造函数中包含class(*)
or 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