Crear matrices heterogéneas en Fortran
Estoy tratando de crear matrices heterogéneas que contienen variables de diferentes tipos, por ejemplo,[ 1.0, 7, "hi" ]
. Traté de incluirclass(*)
otype(*)
en el constructor de matrices (consulte el final del siguiente código), pero gfortran5.2 simplemente lo considera como un error de sintaxis. ¿Hay alguna manera de hacer una matriz de este tipo con un constructor de matrices, o es necesario usar un enfoque diferente (por ejemplo, definir un tipo que contenga cada elemento por separado)?
Más detalles:
El siguiente código es un ejemplo de por qué quiero crear una matriz de este tipo. loschecktype_multi
rutina recibe múltiples argumentos con eloptional
palabra clave, pero este enfoque está claramente limitado debido al número fijo de argumentos. Para permitir un número arbitrario de argumentos, probé elchecktype_array
rutina, pero parece imposible pasar una matriz con diferentes tipos ... Una más prácticacaso puede ser hacer una subrutina para imprimir un número variable de argumentos con varios tipos.
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