Pointers 抽象虚拟接口是Fortran中推荐的编程习惯吗?
在我的代码中,根据用户指定的输入,需要按特定顺序执行不同的子例程。例如,我们可以Pointers 抽象虚拟接口是Fortran中推荐的编程习惯吗?,pointers,fortran,intel-fortran,Pointers,Fortran,Intel Fortran,在我的代码中,根据用户指定的输入,需要按特定顺序执行不同的子例程。例如,我们可以 do TIMELOOP = 1, n if(userinput_1) then call routine_1(..) call routine_2 (..) etc etc elseif (userinput_2) then call routine_3(....) call routine_
do TIMELOOP = 1, n
if(userinput_1) then
call routine_1(..)
call routine_2 (..)
etc etc
elseif (userinput_2) then
call routine_3(....)
call routine_1(....)
endif
enddo
我一直在使用的避免所有这些ifs的解决方案是使用指向过程的指针数组
type ptr_proc
procedure(A_INT), pointer :: proc
end type
type(ptr_proc), allocatable :: ptr(:)
问题是Fortran要求指针proc
始终指向具有定义为A_INT
的相同接口的过程。我不可能做到这一点,因为例程1、例程2等都非常不同
我通过定义以下神奇的界面来克服这个问题
abstract interface
subroutine A_INT
end subroutine
end interface
换句话说,它有一个空接口。带有空接口的例程基本上是例程1、例程2等的包装器 例如,例程_1的包装可以是:
subroutine WRAP_ROUT_1
use MOD_FOR_ROUT_1
call ROUTINE_1( ...) ! - I insert the (inputs, outputs) here which I have from the use statement
end subroutine
然后,在初始化过程中,我将所有指针指向相应的包装程序
if(userinput_1) then
ptr(1)% proc => WRAP_ROUT_1
ptr(2)% proc => WRAP_ROUT_2
etc etc.
elseif ...
endif
然后我的timeloop看起来像
do TIMELOOP = 1, n
do i = 1 , size(ptr)
call ptr(i)% PROC
enddo
enddo
但是,我担心这是否会导致潜在的问题/危险。我的问题实际上归结为在Fortran中使用这种编程实践的后果 这看起来真的是基于意见的。“推荐”的概念通常是基于意见的。谁推荐的?第一种解决方案似乎更容易理解。为什么要实现不那么清晰、更复杂的东西?使用
procedure()、pointer::proc
是合法的。如果你想比较方法,你可能应该包括这个。”换句话说,它有一个空接口。“不:接口不是空的,它是一个没有参数的子例程的接口,有一个指向没有参数的子例程的指针是好的。不过,这与过程()不同(非常)。这是值得考虑的。