3

我可以为 FORTRAN 2003 中的派生数据类型重载条目访问运算符 []、() 或 {}?在以下示例中,我想为派生数据类型“自定义”定义访问方案。

type custom
   integer, dimension(:), allocatable :: a
end type custom

type(custom) :: t

! after some initialization 
! .....
! .....
! .....
!
t%a( (/ 1, 2, 5 /) ) ! return entries located in positions 1, 2, and 5
t{ (/ 1, 2, 5 /) }   ! ?????? I want to define what stuff it should return 

我怎样才能做到这一点?

更新:

请注意,我不想直接使用数组“t%a”并对其进行常规的子数组操作。相反,我想为数据类型“自定义”重新定义数组操作,这样 t{'first'} 应该返回一个指针,即 t%a 或 t%a(1) 中的第一个条目,所以我可以说

t['first']= 18 

或者

print *, t['first']. 

此外,通过额外的重载,我想获得像 t[1] = 18 这样的功能,就像 t['first'] = 18 一样。

4

1 回答 1

4

这取决于您所说的“返回”是什么意思。

本身提供的例子

t%a([1,2,5])   ! Using syntax offered by Fortran 2003

返回任何东西:它是一个subobject。通过引用该子对象,我们可以做各种事情:

print *, t%a([1,2,5])
t%a([1,2,5]) = 27
t%a([1,2,5]) = sin(real(t%a([1,2,5])))

但是仍然没有“返回”的概念。至关重要的是,正如我们将看到的,这些不是表达式。

谈到这个问题,can t[], t(),t{}意味着什么,那么答案很简单,“不”。* 例如,您可能想说:

t[1,2,5] = 1

意思是

t%a[1,2,5] = 1

但这不是要考虑的事情。

可以创建一个类似的表达式

print *, t%ref([1,2,5])

但我们完全处于无法定义的领域。

但是,正如您现在提到的指针,还有更多要说的。虽然首选语法t[1]t["first"]不可用,但我们仍然可以选择类型绑定过程。例如,函数调用t%ref("first")很可能能够返回指向t%a. 例如,t%ref(1)可能像

module reference

  implicit none

  type custom
     integer, dimension(:), allocatable :: a
   contains
     procedure ref
  end type custom

contains

  function ref(t, idx)
    class(custom), target, intent(in) :: t
    integer, intent(in) :: idx
    integer, pointer :: ref

    ref => t%a(idx)
  end function ref

end module reference

  use reference
  implicit none

  type(custom), target :: t
  integer, pointer :: b

  t%a = [1, 2, 3, 4, 5]

  print *, t%a
  b => t%ref(1)  ! Fortran 2008 allows direct assignment
  b = 8          ! but compiler support is very limited.
  print *, t%a

end

如果需要ref,可以将其设为通用,以便t%ref("first")(等)可以接受。


*我的依据是这里t是一个标量。但是,正如 Vladimir F 在评论中提到的那样()[]可能确实意味着事情。第一个与阵列有关,第二个与协阵列有关。那么,语法是一个问题,但这个答案更多地着眼于机制而不是语法。

于 2014-08-30T23:50:49.257 回答