问题
Can I overload entry access operators [], () or {} for derived data types in FORTRAN 2003? In the following example, I want to define access scheme for the derived data type "custom".
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
How can I do that?
Update:
Note that I don't want to use the array "t%a" directly and do conventional sub-array operation on that. Instead, I want to redefine array operation for data type "custom" such that t{'first'} should return a pointer the first entry in t%a or t%a(1) so I can say
t['first']= 18
or
print *, t['first'].
Also with additional overloading I want to get a functionality like t[1] = 18 works like t['first'] = 18.
回答1:
This rather depends on what you mean by "return".
By itself the example offered
t%a([1,2,5]) ! Using syntax offered by Fortran 2003
doesn't return anything: it's a subobject. With a reference to that subobject we can do various things:
print *, t%a([1,2,5])
t%a([1,2,5]) = 27
t%a([1,2,5]) = sin(real(t%a([1,2,5])))
but there's still no concept of "returning". Crucially, as we shall see, these are not expressions.
Coming to the question, can t[]
, t()
, t{}
mean something, then the answer is, simply, "no".* You may want, for example, to say:
t[1,2,5] = 1
to mean
t%a[1,2,5] = 1
but that is not something to consider.
It would be possible to create an expression like
print *, t%ref([1,2,5])
but we're quite in the non-definable territory.
However, as you now mention pointers, there's more to say. Whilst the preferred syntax t[1]
or t["first"]
is not available we still have the option of type-bound procedures. For example, a function call t%ref("first")
may well be able to return a pointer to the first element of t%a
. For example, t%ref(1)
could be like
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
If desired ref
can be made generic so that t%ref("first")
(etc.) is acceptable.
* I'm basing that on the fact that here t
is a scalar. However, as mentioned by Vladimir F in a comment ()
and []
potentially do mean things. The first relates to arrays and the second to co-arrays. Syntax, then, is an issue, but this answer looks more at the mechanism than syntax.
来源:https://stackoverflow.com/questions/25587519/access-operators-overloading-in-fortran-90-or-2003