[英]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
I can then use loop_func
as a pointer when writing my loop. 然后,在编写循环时,可以将
loop_func
用作指针。 Both functions take exactly the same inputs, and are different approaches on tackling the problem based on the value of a
. 这两个函数采用完全相同的输入,并且是基于
a
的值来解决问题的不同方法。 This will allow me to only have one block of code, instead of two nearly identical blocks. 这将使我仅具有一个代码块,而不是两个几乎完全相同的块。 This could apply to subroutines too.
这也可能适用于子例程。
Any ideas how this might be implemented? 任何想法如何实现?
Thank you. 谢谢。
Yes, Fortran has procedure pointers, so you can in effect alias a function name. 是的,Fortran具有过程指针,因此您实际上可以别名一个函数名称。 Here is a code example which assigns to the function pointer "f_ptr" one function or the other.
这是一个代码示例,将一个功能或另一个功能分配给功能指针“ f_ptr”。 Thereafter the program can use "f_ptr" and the selected function will be invoked.
此后,程序可以使用“ 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
Most Fortran implementations do not have a standard way to manipulate function pointers or procedure pointers. 大多数Fortran实现都没有标准的方法来操作函数指针或过程指针。 However, Fortran 2003 and later have something.
但是,Fortran 2003和更高版本具有某些功能。 (See page 6 of this .)
(参见第6页的这个 。)
For the given situation, this will work pretty well in its place: 对于给定的情况,这将很好地代替它:
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
Then just call funcselect
with the extra parameter instead of what you would have done with loop_func
. 然后,只需使用额外的参数调用
funcselect
,而不是使用loop_func
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.