Reputation: 29244
I have a simple user-defined type
use, intrinsic :: iso_fortran_env
implicit none
type :: vector
real(real64) :: data(3)
end type
that has various interfaces defined as well as the assignment operator to and from arrays.
What I need is an abstract interface
interface assignment(=)
procedure v_to_a_assign, a_to_v_assign
end interface
which means I can do things like
type(vector) :: v
real(real64) :: a(3)
a = v
But what I want to do is an array-constructor such as
type(vector) :: v
real(real64) :: q(4)
q = [1d0, v]
! error #8209: The assignment operation or the binary expression operation is
! invalid for the data types of the two operands. [v]
which I could do if v
was an array of real(real64)
. My question here is what binary operation do I need to define to make the above work?
The above is just one example of an implicit conversion of a user type to an array. I want to define the correct operator such that my user type is automaticall converted to an array when needed, like in function arguments, and/or other constructs.
define an interface for the conversion using the keyword real
.
interface real
procedure v_to_array
end interface
contains
function v_to_array(v) result(a)
type(vector), intent(in) :: v
real(real64), dimension(3) :: a
a = v%data
end function
and use it as
q = [1d0, real(v)]
References Array Constructors
Upvotes: 2
Views: 114
Reputation: 21431
The language does not support the implicit conversion you are after.
Reference the array component, either directly using the component within the array constructor:
q = [1.0_real64, v%data]
or write an appropriate accessor function/unary operator.
q = [1.0_real64, .getdata. v]
The implicit conversion you seek would be problematic given the way generic resolution is defined by the language.
As a matter of style, explicit conversions are often preferred - for example user a structure constructor as the expression instead of the user defined assignment when assigning to an object of type vector
, use an accessor function or unary operator when assigning to an array of real. Beyond clarity, user defined assignment does not invoke automatic (re)allocation of the variable on the left hand side of an assignment.
(Fortran does not have an assignment operator - it has an assignment statement.)
Upvotes: 3