Sam*_*Tan 27 alias fortran pointers function subroutine
不确定标题是否放好.建议欢迎.
这就是我想要做的.检查一个条件,然后决定在循环中使用哪个函数.例如:
if (a < 0) then
loop_func = func1
else
loop_func = func2
endif
Run Code Online (Sandbox Code Playgroud)
然后我可以loop_func在编写循环时用作指针.这两个函数都采用完全相同的输入,并且是基于值的解决问题的不同方法a.这将允许我只有一个代码块,而不是两个几乎相同的块.这也适用于子程序.
有什么想法可以实现吗?
谢谢.
M. *_* B. 38
是的,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
Run Code Online (Sandbox Code Playgroud)
大多数 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
Run Code Online (Sandbox Code Playgroud)
然后只需funcselect使用额外的参数进行调用,而不是使用loop_func.