每次以不同的函数作为参数多次调用子例程 [英] Calling a subroutine multiple times with different function as argument each time
问题描述
我是个新手,不知道该术语,所以我无法在网络上找到答案.
I'm enough of a novice to not know the terminology, so I can't search the Web for the answer to this.
在编程中,我不止一次想要做这样的事情.
More than once, in programming, I've wanted to do something like this.
A和B是子例程,c和d是函数. A和B各自在其中多次调用一个函数.
A and B are subroutines, c and d are functions. A and B each call a function multiple times inside them.
call A(c(x))
call A(d(x))
call B(c(x))
call B(d(x))
此结构不起作用.有人告诉我,至少在这种情况下,Fortran不支持函数别名. (大多数涉及别名"的搜索结果都引用别名变量而不是函数,这就是为什么我找不到答案的原因.)
This structure doesn't work. I'm told that Fortran doesn't support aliasing of functions, at least in this context. (Most search results involving "aliasing" refer to aliasing variables rather than functions, which is why I haven't found an answer.)
那么我可以使用什么结构来执行此操作而不必编写多个版本的A和B?
So what structure can I use to do this without having to write multiple versions of A and B?
推荐答案
不是完全确定我了解您想要什么,但是它类似于以下内容吗?
Not totally sure I understand what you want, but is it something like the following?
Program f
Implicit None
Interface
Integer Function c( x )
Implicit None
Integer, Intent( In ) :: x
End Function c
Integer Function d( x )
Implicit None
Integer, Intent( In ) :: x
End Function d
End Interface
Call a( 3, c )
Call a( 4, d )
Call b( 5, c )
Call b( 6, d )
Contains
Subroutine a( x, func )
Integer, Intent( In ) :: x
Interface
Integer Function func( x )
Implicit None
Integer, Intent( In ) :: x
End Function func
End Interface
Write( *, * ) 'In a. Func = ', func( x )
End Subroutine a
Subroutine b( x, func )
Integer, Intent( In ) :: x
Interface
Integer Function func( x )
Implicit None
Integer, Intent( In ) :: x
End Function func
End Interface
Write( *, * ) 'In b. Func = ', func( x )
End Subroutine b
End Program f
Integer Function c( x )
Implicit None
Integer, Intent( In ) :: x
c = 2 * x
End Function c
Integer Function d( x )
Implicit None
Integer, Intent( In ) :: x
d = 10 * x
End Function d
Wot now? gfortran -std=f95 f.f90
Wot now? ./a.out
In a. Func = 6
In a. Func = 40
In b. Func = 10
In b. Func = 60
Wot now?
一种替代方法是过程指针,但是您需要一个f2003编译器,并且这些编译器还不那么普遍-上面的代码可以很好地回到f90上,甚至早于External可以完成您想要的操作,但是错误更少检查功能
An alternative is procedure pointers, but you'll need a f2003 compiler for that and those are not so common yet - the above is fine back to f90 and even earlier than that External will do what you want, but has less error checking capabilities
这篇关于每次以不同的函数作为参数多次调用子例程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!