如何在Fortran中别名函数名称

不知道标题是否正确。 build议欢迎。

这是我想要做的。 检查条件,然后决定在循环中使用哪个函数。 例如:

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

我可以在编写循环时使用loop_func作为指针。 这两个函数都采用完全相同的input,并且是基于a的值来解决问题的不同方法。 这将允许我只有一个代码块,而不是两个几乎相同的块。 这也可以应用于子程序。

任何想法如何实施?

谢谢。

是的,Fortran有过程指针,所以你可以实际上是一个函数名的别名。 这是一个代码示例,它将函数指针“f_ptr”分配给一个函数或另一个函数。 此后,程序可以使用“f_ptr”,所选的function将被调用。

 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_funcloop_func