在现代版本的Fortran中是否有可能将一个类型的参数传递给子程序并使用它来"转换"这种变量?例如,在下面的代码中,我试图在打印之前将默认整数转换为16位整数.
program mwe
! Could use iso_fortran_env definition of int16, but I am stuck with
! old versions of ifort and gfortran.
! use, intrinsic :: iso_fortran_env, only : int16
implicit none
! 16-bit (short) integer kind.
integer, parameter :: int16 = selected_int_kind(15)
call convert_print(123, int16)
contains
subroutine convert_print(i, ikind)
implicit none
integer, intent(in) :: i
integer, intent(in) :: ikind
print*, int(i, ikind)
end subroutine convert_print
end program mwe
Run Code Online (Sandbox Code Playgroud)
使用此示例代码,英特尔Fortran编译器会抱怨这一点
mwe.f(24):错误#6238:在此上下文中需要整数常量表达式.[IKIND]
...
mwe.f(24):错误#6683:种类型参数必须是编译时常量[IKIND]
和gfortran抱怨
(1)中'int'内在的"种类"论证必须是常数
在这种情况下,使用print*, int(i, int16)代替print*, int(i, ikind)当然可以正常工作.但是,如果convert_print在一个没有定义的模块中定义int16那么这将是无用的.
有没有办法将类型参数作为常量传递给子程序?
小智 5
我也有同样的问题.我发现非常不方便,不允许将类型数据类型作为参数传递给过程.在我的情况下,我正在编写一个子程序,只是从文件中读取一个矩阵,并获取我想要的数据类型的对象.我不得不写四个不同的子程序:ReadMatrix_int8(...),ReadMatrix_int16(...),ReadMatrix_int32(...)和ReadMatrix_int64(...)这些只是相同的代码,只有一行不同:
integer(kind=xxxx), allocatable, intent(out) :: matrix(:,:)
Run Code Online (Sandbox Code Playgroud)
只编写一个子程序并将xxxx作为参数传递是有意义的.如果我找到任何解决方案,我会告诉你.但是我担心没有比编写四个子程序更好的解决方案,然后编写一个接口来创建一个通用的过程,如:
interface ReadMatrix
module procedure ReadMatrix_int8
module procedure ReadMatrix_int16
module procedure ReadMatrix_int32
module procedure ReadMatrix_int64
end interface
Run Code Online (Sandbox Code Playgroud)