我想编写一个模块,该模块将根据“用户”在不同文件中提供的功能类型执行一些操作。该函数将作为该模块的“ execute(...)”子例程的参数传递。这基本上是我想要获得的,但是我不知道这是否可行以及如何正确执行。
module mod1
contains
subroutine execute(func)
interface func
real function func1(a,b)
real a,b
end function
real function func2(a,b,c)
real a,b,c
end function
! more similar functions here
end interface func
! -------------------
! here some how choose between func1 or func2
! and do the calculations
if(func1) then ...
else if(func2) ...
! -------------------
endsubroutine execute
endmodule mod1
------------------------------------------
program
use mod1
call execute(test)
contains
real function test(a,b)
real a,b
test = a + b
end function
end program
我知道这段代码不会编译,但这只是草图。就目前而言,对我来说,解决该问题的唯一丑陋解决方案是为execute子例程编写许多替代方法,即execute_1,execute_2,并且根据测试功能,用户必须选择适当的execute_X函数。
对于这个问题有更好的解决方案吗?
提前致谢。KK
您也可以将接口放在模块头中,并像这样对func1和func2使用procedure属性。如果您想在其他地方使用它们,这将很有用,因为您只在一个地方定义它们。
module mod1
abstract interface
real function f1(a,b)
real,intent(in) :: a,b
end function f1
real function f2(a,b,c)
real,intent(in) :: a,b,c
end function f2
end interface
contains
subroutine execute(func1, func2)
procedure(f1),optional :: func1
procedure(f2),optional :: func2
!...
if (present(func1)) x = func1(a, b)
if (present(func2)) x = func2(a, b, c)
end subroutine execute
end module mod1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句