赋值的 Fortran 语法

Fortran syntax for assignments

Fortran 语法快把我逼疯了!任何人都可以解释我如何 调用 作业(我很确定这也不是正确的术语......)。我正在尝试 根据值类型 分配类型。我有以下内容:

module test_module

   implicit none

   type :: mytype

      integer   :: i
      real      :: r
      logical   :: l

   contains

      generic :: assignment(=) => mytype_to_type
      procedure, pass(me) :: mytype_to_type

   end type mytype

contains

   subroutine mytype_to_type(t, me)

      implicit none

      class(*), intent(inout)   :: t
      class(mytype), intent(in) :: me

      !.. process based on input type
      select type (t)
         type is (integer)
            t = me%i
         type is (real)
            t = me%r
         type is (logical)
            t = me%l
         class default
            stop "none"
            return
      end select

   end subroutine mytype_to_type

end module test_module

program test

    use test_module

    implicit none

    type(mytype) :: t_type

    integer :: i = 1
    real    :: r = 1.
    logical :: l = .true.

    t_type = i                 !! how is this supposed to work?

    select type(t_type)

        type is (integer)
            write(*,*) "is int"
        type is (real)
            write(*,*) "is real"
        type is (logical)
            write(*,*) "is logical"
        class default
            return

    end select


end program test

这还能行吗?谁能帮我解决这个问题?

谢谢!

在支持定义赋值的子例程中,两个参数是这样的,第一个对应于赋值语句的左侧,第二个对应于右侧。1

这里,那么你提供的子程序就是从一个my_type表达式赋值给一个无限多态对象。这不是你想要的,看到左边的 t_type

相反,您应该提供已定义的赋值 一个 my_type 对象。

subroutine stuff_to_mytype(me,t)
  class(mytype), intent(out) :: me
  class(*), intent(in) :: t

  !.. process based on input type
  select type (t)
     type is (integer)
        me%i = t
     type is (real)
        me%r = t
     type is (logical)
        me%l = t
     class default
        stop "none"
        return
  end select

end subroutine stuff_to_mytype

就是说,您可以使用针对您支持的每种类型的特定子例程来执行此操作,而不是使用具有通用分辨率的无限多态右侧。在这种情况下,您还可以考虑通用结构构造函数 (t_type=mytype(i)).


1准确地说,第二个参数是括号中的右侧。