fortran中具有相同结构和不同子例程的两种派生类型

fortran中具有相同结构和不同子例程的两种派生类型,fortran,Fortran,是否可以将不同的子例程与具有相同结构的派生类型中的过程相链接 我使用的是派生类型,我的想法是用相同的结构链接不同的子例程,这样它就可以作为参数传递 我想到了子程序重载。但是,它需要不同类型的参数,这是没有帮助的 下面的代码没有编译,但它有其主要思想 module mod1 implicit none type foo_data integer :: a, b contains procedure :: oper !I know that this is

是否可以将不同的子例程与具有相同结构的派生类型中的过程相链接

我使用的是派生类型,我的想法是用相同的结构链接不同的子例程,这样它就可以作为参数传递

我想到了子程序重载。但是,它需要不同类型的参数,这是没有帮助的

下面的代码没有编译,但它有其主要思想

module mod1
  
  implicit none
  
  type foo_data
    integer :: a, b
  contains
    procedure :: oper   !I know that this isn't allowed because some coding is missing
  end type foo_data

  type(foo_data) :: foo1
  type(foo_data) :: foo2

contains

  subroutine add(a,b,c)

    integer, intent(in)  :: a, b
    integer, intent(out) :: c

    c=a+b

  end subroutine add
  subroutine sub(a,b,c)

    integer, intent(in)  :: a, b
    integer, intent(out) :: c

    c=a-b

  end subroutine sub

end module mod1

program main

 use mod1

 implicit none

 Integer :: c, d

 !link add with foo1 using oper or another idea
 !link sub with foo2 using oper or another idea

 foo1%a=1
 foo1%b=2

 foo2%a=2
 foo2%b=1

 call compute(foo1,c)
 write(*,*) c

 call compute(foo2,d)
 write(*,*) d

contains

  subroutine compute(foo,r)
  
    type(foo_data) :: foo

    integer, intent(out) :: r

    call foo%oper(foo%a,foo%b,r)

  end subroutine compute

end program main

我不太确定您想做什么,但看起来您可能只是想将
oper
作为过程指针,而不是类型绑定过程?我不确定。您能给出一个使用oper作为过程指针的例子吗?对于组件
过程(add),pointer::oper
,然后
foo1%oper=>add;foo2%oper=>sub
,等等。如果我理解正确,另一种方法是使用一个抽象基类型,然后使用两个不同的扩展,将类型绑定过程oper设置为适当的值。然后将变量分配到适当的类型。我同意@IanBush。这是实现它的最干净的方法。请注意,
compute
过程需要使用多态伪参数,即
class(foo\u parent)::foo
。如果您需要更具体的示例实现,请给我们一个提示。