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

查看:188
本文介绍了如何在Fortran中为函数名称创建别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道标题是否合适。建议welcome。



这是我想要做的。检查一个条件,然后决定在循环中使用哪个函数。例如:

  if(a <0)then 
loop_func = func1
else
loop_func = func2
endif

然后我可以使用 loop_func 作为写入我的循环时的指针。两个函数都采用完全相同的输入,并且是基于 a 的值解决问题的不同方法。这将允许我只有一个代码块,而不是两个几乎相同的块。这可能也适用于子例程。



任何想法如何实现?



谢谢。

解决方案

是的,Fortran具有过程指针,所以你可以实际上是一个函数名称的别名。这是一个代码示例,它将函数指针f_ptr分配给一个函数或另一个函数。此后,程序可以使用f_ptr,并调用所选函数。

  module ExampleFuncs 

隐式无

包含

函数f1(x)
real :: f1
实数,意图(in):: x

f1 = 2.0 * x

返回
结束函数f1


函数f2(x)
real :: f2
real,意图(in):: x

f2 = 3.0 * x ** 2

返回
结束函数f2

结束模块ExampleFuncs


程序test_func_ptrs

使用ExampleFuncs
隐式无

抽象接口
函数func(z)
real :: func
real,intent(in):: z
结束函数func
结束接口

过程(func) ,pointer :: f_ptr => null()

real :: input

write(*,'(/Input test value:)',advance =no)
read (*,*)输入

if(输入<0)然后
f_ptr => f1
else
f_ptr => f2
end if

write(*,'(/evaluate function:,ES14.4)')f_ptr(input)

stop

结束程序test_func_ptrs


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. 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?

Thank you.

解决方案

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天全站免登陆