简体   繁体   English

如何让通用子例程在假定大小数组的fortran中工作

[英]How to have generic subroutine to work in fortran with assumed size array

I have an interface block to define a generic subroutine which have an assumed size array as dummy argument (in order to be able to act on 'the middle' of a passed array, like a C pointer) and it does not compile. 我有一个接口块来定义一个通用的子例程,该例程具有一个假定的大小数组作为伪参数(以便能够在传递的数组的“中间”(如C指针)上操作)并且不会编译。 Here is simple exemple: 这是一个简单的例子:

module foo

  interface sub
     module procedure isub
     module procedure dsub
  end interface

  contains

  subroutine isub(a,n)
    integer, intent(in) :: a(*), n
    integer :: i
    print*, 'isub'
    do i=1,n
     print*, a(i)
    enddo
  end subroutine isub

  subroutine dsub(a)
    real(8), intent(in) :: a(*)
    integer, intent(in) :: n
    integer :: i
    print*, 'dsub'
    do i=1,n
     print*, a(i)
    enddo
  end subroutine dsub

end module foo

program test

  use foo

  implicit none

  integer :: ai(4)
  real(8) :: ad(4)

  ai=(/1,2,3,4/)
  ad=(/1.,2.,3.,4./)

  call sub(ai,3)
  call sub(ad,3)

  call isub(ai(2),3)
  !call sub(ai(2),3)

end program test

The commented line does not compile, whereas it is ok when calling directly the subroutine with call isub(ai(2),3) (tested with gfortran and ifort). 带注释的行不会编译,但是直接通过call isub(ai(2),3)子例程(使用gfortran和ifort测试)可以。 Why and is it possible to have it to work with call sub(ai(2),3) ? 为什么并且可以使其与call sub(ai(2),3)

edit: with ifort, it says: 编辑:与ifort,它说:

$ ifort overload.f90
overload.f90(37): error #6285: There is no matching specific subroutine for this generic subroutine call.   [SUB]
  call sub(ai(2),3)
-------^
compilation aborted for overload.f90 (code 1)

Thanks 谢谢

You are passing a scalar to a function that is expecting an array. 您正在将标量传递给需要数组的函数。 Try 尝试

call sub(ai(2:2))

which is passing an array of length one. 传递长度为1的数组。 I'm wondering why call isub(ai(2)) is accepted, though... 我想知道为什么call isub(ai(2)) ,但是...

To answer your new question (partly in the comments): 要回答您的新问题(部分在评论中):

If you restrict yourself to contiguous arrays, you can use call sub(ai(2:4)) without loss of performance using deferred shape arrays: 如果将自己限制为连续数组,则可以使用call sub(ai(2:4)) 而不会使用延迟形状数组降低性能:

subroutine isub(a)
  integer,intent(in) :: a(:)
  integer            :: i

  print*, 'isub'
  do i=1,size(a)
    print*, a(i)
  enddo
end subroutine isub

There are no temporary arrays created with ifort or gfortran . 没有使用ifortgfortran创建的临时数组。 You can check for this using: 您可以使用以下方法进行检查:

  • ifort -check arg_temp_created

  • gfortran -Warray-temporaries

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM