我正在使用 FORTRAN oop 功能进行编程。现在我有一个子程序,它以另一个子程序作为参数。但我希望子程序以无限多态子程序作为参数以及普通子程序。例如我有:
subroutine PassFunc(MyFunc, MyInput)
class(*), intent(inout) :: MyInput
interface
subroutine MyFunc(A, B)
class(*), intent(in) :: A
class(*), intent(out) :: B
endsubroutine MyFunc
endinterface
class(*), allocatable :: FuncRes
select type(MyInput)
type is(real(8))
allocate(real(8)::FuncRes)
select type(FuncRes)
type is(real(8))
call MyFunc(MyInput, FuncRes)
MyInput = MyInput + FuncRes**2
endselect
type is(complex(8))
endselect
endsubroutine PassFunc
!Input Functions
subroutine Func1(A, B)
class(*), intent(in) :: A
class(*), intent(out) :: B
select type(A)
type is(real(8))
select type(B)
type is(real(8))
B = A + 1
endselect
type is(complex(8))
select type(B)
type is(complex(8))
B = A - 1
endselect
endselect
endsubroutine Func1
subroutine Func2(A, B)
real(8), intent(in) :: A
real(8), intent(out) :: B
B = A + 1
endsubroutine Func2
问题:
我只被允许将无限的多态子例程传递给“PassFunc”。我无法传递普通函数(没有类(*)的函数)。有没有办法让“PassFunc”具有其他类型的功能?(示例:Func1 有效,但 Func2 无效。我使用 IVF 时遇到了访问冲突,虽然它在编译时没有报错。是否可以使其工作?如果可以,我可以在不修改的情况下使用其他子程序。 )
在这种情况下,“FuncRes”变量的类型取决于“MyInput”。现在我知道的唯一方法是使用嵌套选择类型。但实际上没有必要这样做,因为“FuncRes”和“MyInput”永远是同一个类型。有没有办法减少嵌套的select类型?(如果我有很多中间变量,那将是一场灾难。)