Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Fortran 在子例程中传递和使用可选掩码_Fortran - Fatal编程技术网

Fortran 在子例程中传递和使用可选掩码

Fortran 在子例程中传递和使用可选掩码,fortran,Fortran,我将可选掩码传递给子例程。在这个例行程序中,我有许多类似的陈述 ... if (present(Mask)) then where(Mask) y(:) = A(:)*B(:) end where else y(:) = A(:)*B(:) end if ... 这在代码复制方面是非常丑陋的。有没有更好的建议?我的代码中有很多类似的语句,我需要在整个数组上执行这些操作 编辑: 至少有一部分问题可以通过基本函数来解决。因为我在右边有相同的操作,所以我可以写 ... if (p

我将可选掩码传递给子例程。在这个例行程序中,我有许多类似的陈述

...
if (present(Mask)) then
  where(Mask)
    y(:) = A(:)*B(:)
  end where
else
  y(:) = A(:)*B(:)
end if
...
这在代码复制方面是非常丑陋的。有没有更好的建议?我的代码中有很多类似的语句,我需要在整个数组上执行这些操作

编辑: 至少有一部分问题可以通过基本函数来解决。因为我在右边有相同的操作,所以我可以写

...
if (present(Mask)) then
  where(Mask)
    y(:) = multiply(A(:),B(:))
  end where
else
  y(:) = multiply(A(:),B(:))
end if
...
elemental real function multiply(a,b)
  real, intent(in) :: a,b
  multiply = a*b
end function
这样,我至少有一个操作位置。

可以选择(双关语)不使用可选参数,而是编写一个通用接口。比如说,不是写作

subroutine bar(arg0, opt)
  integer, intent(inout) :: arg0
  integer, intent(in), optional :: opt
  arg0 = int(4 * atan(1.))
  if (present(opt)) arg0 = arg0 + opt
module foo
你能行

interface bar
  module procedure bar0
  module procedure bar1
end interface bar

contains

  subroutine bar0(arg0)
     integer, intent(inout) :: arg0
     arg0 = int(4 * atan(1.))
  end subroutine bar0

  subroutine bar1(arg0, opt)
     integer, intent(inout) :: arg0
     integer, intent(in) :: opt
     arg0 = arg0 + opt
  end subroutine bar1

end module foo

program bah
  use foo
  integer :: a0 = 1, a1 = 42
  call bar(a0)
  print *, a0
  call bar(a0, a1)
  print *, a0
end program bah
您可能从这种方法中获得的一个优势是bar0 bar1可以让编译器更好地进行优化
密码。
if(present(opt))
结构可能会妨碍您。

有很多讨论。有什么适合你的吗?谢谢你提供链接。在我看来,没有直接的解决办法,我的问题也非常相似。我想我现在可以知道了。这是一个非常好的主意,特别是从性能的角度来看。不幸的是,在我的例子中,我将这个掩码传递给许多子例程,这意味着我还需要为所有这些例程编写接口。此外,我仍然会有右侧的代码复制。但这让我想到了另一个想法——我可以使用基本函数,这样至少可以消除右侧重复的赋值。是的,能够将
可选的
参数向下传递到调用链是一个很好的功能。当我使用
optional
参数时,我构造代码以最小化
if(present(arg))
测试(即通常两个代码块)。