首页 > 解决方案 > 用户定义类型作为基本子程序的参数?

问题描述

在我的代码中,我有一个基本的子程序,基本上是这样的:

elemental subroutine calc_stuff (x, a, b, c)
   real, intent(in)  :: a, b, c
   real, intent(out) :: x

   x = a/b + c

end subroutine calc_stuff

我改成这样:

elemental subroutine calc_stuff (x, a, t)
   real,         intent(in)  :: a
   type(mytype), intent(in)  :: t
   real,         intent(out) :: x

   x = a/t%b + t%c

end subroutine calc_stuff

wheremytype是一个包含一些标量realand的类型integer,以及一个real, allocatable数组。成员bcreals,使第二个版本与第一个基本相同。

第二个版本在各种编译器(Cray、Intel、NEC、GFortran)上编译得很好,但现在我读到元素子例程的标准状态:

所有虚拟参数都必须是标量,并且不能具有 ALLOCATABLE 或 POINTER 属性。

因此,在将用户定义的类型传递给元素子例程时,我的代码是否不符合标准,但所有编译器都“知道”我想要什么,因为我只使用类型中的标量而不是可分配数组?还是我误解了标准的措辞而第二版一切正常?

标签: fortranparameter-passing

解决方案


虚拟参数t是标量1,没有指针属性,也没有可分配属性。它不违反条件。

类型组件的属性与类型本身的属性无关。


1 Being of derived type doesn't make an object necessarily non-scalar. Even with multiple, or array components, the object itself may still be scalar. A derived type array is an array with element(s) of that type. Think also of a character object like character(len=3) name: it is scalar but consists of multiple substrings.


推荐阅读