将用户类型转换为数组的通用接口

Generic interface to convert user type to array

我有一个简单的用户定义类型

use, intrinsic :: iso_fortran_env
implicit none

type :: vector
    real(real64) :: data(3)
end type

定义了各种接口以及数组的赋值运算符。

我需要的是抽象接口

interface assignment(=)
   procedure v_to_a_assign, a_to_v_assign
end interface    

这意味着我可以做类似

的事情
type(vector) :: v
real(real64) :: a(3)
a = v

但我想做的是一个数组构造函数,例如

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]

如果 vreal(real64) 的数组,我可以这样做。 我的问题是我需要定义什么二元运算才能使上述工作正常进行?

以上只是将用户类型隐式转换为数组的一个示例。我想定义正确的运算符,以便我的用户类型 automaticall 在需要时转换为数组,例如在函数参数中,and/or 其他构造。


解决方案

使用关键字 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

并将其用作

q = [1d0, real(v)]

参考资料 Array Constructors

该语言不支持您进行的隐式转换。

引用数组组件,或者直接使用数组构造函数中的组件:

q = [1.0_real64, v%data]

或编写适当的访问器 function/unary 运算符。

q = [1.0_real64, .getdata. v]

考虑到语言定义通用解析的方式,您寻求的隐式转换会有问题。

就风格而言,通常首选显式转换 - 例如,在分配给类型 vector 的对象时,使用结构构造函数作为表达式而不是用户定义的分配,使用访问函数或分配给实数数组时的一元运算符。除了清楚之外,用户定义的赋值不会调用赋值左侧变量的自动(重新)分配。

(Fortran 没有赋值运算符 - 它有赋值语句。)