类型绑定过程给出关于非多态传递对象伪参数的错误

Type-bound procedure gives error about non-polymorphic passed-object dummy argument

我正在尝试编译下面的 Fortran 模块(使用 gfortran 7.2.0)。重点是定义一个派生类型,该派生类型又包含来自 bspline-fortran 库 (https://github.com/jacobwilliams/bspline-fortran) 的派生类型 bspline_3d 的两个实例。然后我想定义一个类型绑定过程,该过程将依次调用这两种类型的类型绑定 evaluate 过程,并且 return 结果作为具有两个元素的数组。

当我尝试编译下面的模块时,我收到一条错误消息

     procedure  :: evaluate => evaluate_2d
             1
Error: Non-polymorphic passed-object dummy argument of 'evaluate_2d' at (1)

我对错误信息一无所知。

我设法编译了在这里找到的简单示例程序:http://fortranwiki.org/fortran/show/Object-oriented+programming 据我所知,唯一的区别是在我的例子中,"passed-object" (this ) 本身有派生类型的成员变量 (type(bspline_3d) :: fvx, fvy),而这些成员变量又可能包含各种东西。

module interpolator_module

use bspline_module
use parameters, only: WP

implicit none

private
public :: interpolator

type :: interpolator
    type(bspline_3d) :: fvx, fvy
    contains
        private
        procedure  :: evaluate => evaluate_2d
end type interpolator

contains
    function evaluate_2d(this, X, t) result(V)
        implicit none
        ! inputs
        type(interpolator),     intent(inout) :: this
        real(WP), dimension(2), intent(in)    :: X
        real(WP),               intent(in)    :: t
        ! output
        real(WP), dimension(2)                :: V
        ! local variables
        integer                               :: iflag
        integer, parameter                    :: d = 0

        call this%fvx%evaluate(X(1), X(2), t, d, d, d, V(1), iflag)
        call this%fvy%evaluate(X(1), X(2), t, d, d, d, V(2), iflag)
    end function
end module interpolator_module

传递的伪参数 this 必须始终是多态的。这意味着它必须是

 class(interpolator),     intent(inout) :: this

而不是

 type(interpolator),     intent(inout) :: this

这是 type-bound 程序的基本要求。否则您无法使用扩展类型的过程 (children)。

对于像

这样定义的类型绑定过程
type my_type
 contains
  procedure :: proc
end type

类型绑定过程有一个传递的参数。即当

type(my_type) my_obj
call my_obj%proc

被使用,对象my_obj在参数列表中。 proc 定义为

subroutine proc(me)
  type(my_type) me   ! Not correct
end subroutine

然后 call my_obj%proc 就像 call proc%(my_obj)1 那是错误消息的 "passed-object dummy argument" 部分。

在上面 proc 的定义中,传递对象伪参数 type(my_type) me 是非多态的。您可以在其他地方阅读有关多态性的信息,但要回答这个问题:传递的对象伪参数可能不是非多态的。它必须是多态的,使用 class(my_type) me:

声明
subroutine proc(me)
  class(my_type) me   ! Polymorphic, declared type my_type
end subroutine

这意味着可以传递 my_type 类型或扩展 my_type 类型的对象。这是 Fortran 语言的要求。

简而言之:改变你的

type(interpolator),     intent(inout) :: this

class(interpolator),     intent(inout) :: this

更复杂的是,例如,旧版本的 gfortran 在理解多态性之前理解类型绑定过程。这意味着周围有一些错误使用非多态传递对象的例子。


1 我特意将绑定名称保留为 proc 与过程名称相同。在问题的上下文中,它将是 call my_obj%evaluate(...) 就像 call evaluate_2d(my_obj, ...).