Fortran syntax for assignments

微笑、不失礼 提交于 2019-12-23 03:56:35

问题


The Fortran syntax is driving me mad! Can anyone explain how I can call the assignment (I'm pretty sure that is not the right terminology either...). I'm trying to assign a type according to the value type. I have the following:

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

Would this even work? Could anyone help me with this?

Thanks!


回答1:


In a subroutine supporting defined assignment the two arguments are such that the first corresponds to the left-hand side of the assignment statement and the second the right-hand side.1

Here, then the subroutine you provide is assignment from a my_type expression to an unlimited polymorphic object. This isn't what you want, seeing t_type on the left.

Instead, you should provide defined assignment to a my_type object.

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

That said, you could do this with a specific subroutine for each type you support, rather than an unlimited polymorphic right-hand side, with generic resolution. In this case you could also consider generic structure constructors (t_type=mytype(i)).


1 Precisely, the second argument is the right-hand side enclosed in parentheses.



来源:https://stackoverflow.com/questions/50839842/fortran-syntax-for-assignments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!