如何在 Fortran 中为函数名称设置别名 [英] How to alias a function name in Fortran

查看:53
本文介绍了如何在 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.

有什么想法可以实现吗?

Any ideas how this might be implemented?

谢谢.

推荐答案

是的,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆