如何在 Fortran 中为函数名起别名 [英] How to alias a function name in Fortran
问题描述
不确定标题是否正确.欢迎提出建议.
Not sure if the title is well put. Suggestions welcome.
这就是我想要做的.检查条件,然后决定在循环中使用哪个函数.例如:
Here's what I want to do. Check a condition, and then decide which function to use in a loop. For example:
if (a < 0) then
loop_func = func1
else
loop_func = func2
endif
然后我可以在编写循环时使用 loop_func
作为指针.这两个函数都采用完全相同的输入,并且是根据 a
的值解决问题的不同方法.这将允许我只有一个代码块,而不是两个几乎相同的块.这也适用于子程序.
I can then use loop_func
as a pointer when writing my loop. Both functions take exactly the same inputs, and are different approaches on tackling the problem based on the value of a
. This will allow me to only have one block of code, instead of two nearly identical blocks. This could apply to subroutines too.
任何想法如何实现?
谢谢.
推荐答案
是的,Fortran 有过程指针,所以实际上你可以给函数名取别名.这是一个代码示例,它将一个函数或另一个函数分配给函数指针f_ptr".此后程序可以使用f_ptr"并调用所选函数.
Yes, Fortran has procedure pointers, so you can in effect alias a function name. Here is a code example which assigns to the function pointer "f_ptr" one function or the other. Thereafter the program can use "f_ptr" and the selected function will be invoked.
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 中为函数名起别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!