类似于@VladimirF 的回答,但请您澄清一下
我实际上并不需要通用分辨率;valuea1 和 valuea2 接受相同类型的参数来解决我想到的问题,我只想绑定到一个类型扩展中的 valuea1 和另一种类型扩展中的 valuea2。
那么,这里的基本(抽象)类型定义了一个延迟类型绑定过程value()
,其中一个接口class(a)
作为传递的参数。可以添加其他参数。每个扩展类型都用自己的过程定义/覆盖这个类型绑定过程。
这意味着在我们的最终子程序调用test_sub
中,class(a)
虚拟参数确实有一个%value()
.
module types
! The base type
type, abstract :: a
contains
procedure(value_if), deferred :: value
end type a
! The interface for the type-bound procedures
abstract interface
subroutine value_if(var)
import a
class(a) var
end subroutine value_if
end interface
! The extending types, overriding the value subroutine
type, extends(a) :: a1
contains
procedure :: value => value_a1
end type a1
type, extends(a) :: a2
contains
procedure :: value => value_a2
end type a2
contains
subroutine value_a1(var)
class(a1) var
print*, "Value of a1"
end subroutine value_a1
subroutine value_a2(var)
class(a2) var
print*, "Value of a2"
end subroutine value_a2
end module types
program test
use types
type(a1) x
type(a2) y
call x%value
call y%value
call test_sub(x)
call test_sub(y)
contains
subroutine test_sub(var)
class(a) var
call var%value ! This is defined
end subroutine test_sub
end program test
这会产生输出
a1
的值 a2
的值 a1
的值 a2 的值