[英]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.