簡體   English   中英

如何在Fortran中為函數名稱添加別名

[英]How to alias a function name in Fortran

不確定標題是否正確。 歡迎提出建議。

這就是我想要做的。 檢查條件,然后決定在循環中使用哪個函數。 例如:

if (a < 0) then
    loop_func = func1
else
    loop_func = func2
endif

然后,在編寫循環時,可以將loop_func用作指針。 這兩個函數采用完全相同的輸入,並且是基於a的值來解決問題的不同方法。 這將使我僅具有一個代碼塊,而不是兩個幾乎完全相同的塊。 這也可能適用於子例程。

任何想法如何實現?

謝謝。

是的,Fortran具有過程指針,因此您實際上可以別名一個函數名稱。 這是一個代碼示例,將一個功能或另一個功能分配給功能指針“ f_ptr”。 此后,程序可以使用“ f_ptr”,並且所選功能將被調用。

module ExampleFuncs

   implicit none

contains

function f1 (x)
  real :: f1
  real, intent (in) :: x

  f1 = 2.0 * x

  return
end function f1


function f2 (x)
   real :: f2
   real, intent (in) :: x

   f2 = 3.0 * x**2

   return
end function f2

end module ExampleFuncs


program test_func_ptrs

    use ExampleFuncs
    implicit none

   abstract interface
      function func (z)
         real :: func
         real, intent (in) :: z
      end function func
   end interface

   procedure (func), pointer :: f_ptr => null ()

   real :: input

   write (*, '( / "Input test value: ")', advance="no" )
   read (*, *) input

   if ( input < 0 ) then
      f_ptr => f1
   else
      f_ptr => f2
   end if

   write (*, '(/ "evaluate function: ", ES14.4 )' )  f_ptr (input)

   stop

end program test_func_ptrs

大多數Fortran實現都沒有標准的方法來操作函數指針或過程指針。 但是,Fortran 2003和更高版本具有某些功能。 (參見第6頁的這個 。)

對於給定的情況,這將很好地代替它:

 function func1 (p1, p2, etc)
 ...  as you have it already
 end

 function func2 (p1, p2, etc)
 ...  as you have it already
 end

 function funcselect (a, p1, p2, etc)
     if (a < 0) then
          x = func1 (p1, p2, etc)
     else
          x = func2 (p1, p2, etc)
     endif
 end

然后,只需使用額外的參數調用funcselect ,而不是使用loop_func

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM