Fortran语法让我发疯!任何人都可以解释我如何调用作业(我'm pretty sure that is not the right terminology either...). I' m试图 assign a type according to the value type . 我有以下内容:
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
对象提供已定义的赋值 .也就是说,您可以使用针对您支持的每种类型的特定子例程执行此操作,而不是使用通用分辨率的无限多态右侧 . 在这种情况下,您还可以考虑通用结构构造函数(
t_type=mytype(i)
) .1确切地说,第二个参数是括在括号中的右侧 .