不确定标题是否恰当,欢迎提出建议。
我想要做的是:检查一个条件,然后在循环中决定使用哪个函数。例如:
if (a < 0) then
loop_func = func1
else
loop_func = func2
endif
我可以使用loop_func
作为指针来编写我的循环。这两个函数接受完全相同的输入,并且是根据a
的值处理问题的不同方法。这将使我只有一个代码块,而不是两个几乎相同的代码块。这也可以应用于子程序。有任何想法如何实现吗?
谢谢。
不确定标题是否恰当,欢迎提出建议。
我想要做的是:检查一个条件,然后在循环中决定使用哪个函数。例如:
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
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
。
(a<0)
,它要复杂得多。而且这不仅仅是一个简单的循环,函数将被用于多个循环中。为了让你有一个大致的了解,这个函数将会被调用超过800万次,每次迭代100次。 - Samuel Tan