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

Sky*_*010 1 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
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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

我怎样才能防止这种情况发生?

routine_kind8可以定义的子程序定义如下:

subroutine routine_kind8(variable)
implicit none
integer(8), intent(in):: variable

call api_write_data_to_file(variable)

end subroutine routine
Run Code Online (Sandbox Code Playgroud)

api_write_data_to_fileapi中的函数where 可以接受任何类型的函数.但是,我无法在参数列表中动态定义种类类型.因此,我必须根据变量的类型调用此例程的不同版本.我可以或者更准确地说不想api_write_data_to_file直接打电话.相反,我想把它称为内部routine_kind8

Ale*_*ogt 5

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

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
Run Code Online (Sandbox Code Playgroud)

您可以使用该select case语句进一步确定如何继续以及要调用的其他子例程.或者,全部跳过select case语句并api_write_data_to_file直接传递所有内容.

或者,您可以以相同的方式创建interfaceapi_write_data_to_file():

  interface api_write_data_to_file
    subroutine api_write_data_to_file(variable)
      class(*),intent(in)  :: variable
    end subroutine
  end interface
Run Code Online (Sandbox Code Playgroud)

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