Reputation: 401
Is it possible to refer to a derived type field in Fortran dynamically? I want to achieve something to the effect of what can be done in Matlab:
fldnm = 'fred';
s.(fldnm) = 18;
y = s.(fldnm)
See these links (for Matlab examples): http://blogs.mathworks.com/loren/2005/12/13/use-dynamic-field-references/ http://www.mathworks.com/help/matlab/matlab_prog/generate-field-names-from-variables.html
Thanks!
Upvotes: 0
Views: 132
Reputation: 21431
No. Perhaps you need to store both the field name and value in a data object, rather than trying to use components for the field name.
Otherwise you would need to wrap the reference or definition of the component of the object of derived type with a SELECT CASE statement or similar.
TYPE :: t
INTEGER :: fred
INTEGER :: roger
INTEGER :: bill
END TYPE t
SUBROUTINE set(object, name, value)
TYPE(t), INTENT(INOUT) :: object
CHARACTER(*), INTENT(IN) :: name
INTEGER, INTENT(IN) :: value
SELECT CASE (name)
CASE ('fred') ; object%fred = value
CASE ('roger') ; object%roger = value
CASE ('bill') ; object%bill = value
END SELECT
END SUBROUTINE set
FUNCTION get(object, name)
TYPE(t), INTENT(IN) :: object
CHARACTER(*), INTENT(IN) :: name
INTEGER :: get
SELECT CASE (name)
CASE ('fred') ; get = object%fred
CASE ('roger') ; get = object%roger
CASE ('bill') ; get = object%bill
END SELECT
END FUNCTION get
TYPE(t) :: s
CALL set(s, 'fred', 18)
y = get(s, 'fred')
Upvotes: 2