fortran调用子程序取决于类型值错误



我想根据参数的种类值调用一个子例程。我尝试了以下操作,但出现了错误。

parameter, integer:: kind=4
integer(kind):: variable
if (kind==8) then
    call routine_kind8(variable)
elseif(kind==4) then
    call routine_kind4(variable)
endif

我得到以下错误:

call routine_kind8(variable)
                   1
Error: Type mismatch in argument 'variable' at (1); passed INTEGER(4) to INTEGER(8)

我该如何防止这种情况发生?

子程序routine_kind8可以定义如下:

subroutine routine_kind8(variable)
implicit none
integer(8), intent(in):: variable
call api_write_data_to_file(variable)
end subroutine routine

其中CCD_ 2是来自可以接受任何类型的api的函数。但是,我不能在参数列表中动态定义种类类型。因此,我有必要根据变量的种类类型调用这个例程的不同版本。我可以或者更确切地说不想直接呼叫api_write_data_to_file。相反,我想在routine_kind8 内部调用它

如果您使用的是一个相当新的编译器,您可能会研究无限多态性来实现您的目标。然后,您甚至可以将不同的类型传递给同一个子例程:

module test_mod
contains
  subroutine print_type( input )
    class(*),intent(in)  :: input
    select type(input)
    type is (integer(kind=4))
      print *, "Got an integer of kind 4"
    type is (integer(kind=8))
      print *, "Got an integer of kind 8"
    type is (real)
      print *, "Got a real number"
    type is (complex)
      print *, "Got a complex number"
    end select
  end subroutine
end module
program test
use test_mod
  call print_type( 1_4 )
  call print_type( 1_8 )
  call print_type( 1. )
  call print_type( (1.,1.) )
end program

您可以使用select case语句来进一步决定如何继续以及要调用哪些子例程。或者,一起跳过select case语句,将所有内容直接传递给api_write_data_to_file

或者,您可以以相同的方式为api_write_data_to_file()创建一个interface块:

  interface api_write_data_to_file
    subroutine api_write_data_to_file(variable)
      class(*),intent(in)  :: variable
    end subroutine
  end interface

然后,您不需要包装器来调用api_write_data_to_file()

具有常量表达式条件的if构造与条件编译不同。死代码消除也不适用于确保只处理其中一个块。

这意味着,当你有声明integer(kind=4) variable时,你仍然有一行写着

call routine_kind8(variable)

其期望CCD_ 13自变量。

例如,您可以使用带有预处理器的条件编译,但更好的方法可能是使用通用分辨率:

parameter, integer:: kind=4
integer(kind):: variable
call routine(variable)

在创建routine_kind4routine_kind8的过程中,出现了类似的情况

interface routine
  procedure routine_kind4    ! Defined at some point
  procedure routine_kind8
end interface

相关内容

最新更新