0

现代 Fortran(90、2003 甚至 2008)是否有可能拥有一个自定义类型,默认情况下会访问其中一个属性:

program test
    use iso_fortran_env
    type MYTYPE_t
        real(real64) :: data
    end type MYTYPE_t

    type(MYTYPE_T) :: test
    real(real64) :: foo

    ! This works
    test%data = 5.0
    ! Is there a way to be able things like this:
    test = 5.0
    print*, sqrt(test)

    foo = test + 3
end program
4

1 回答 1

1

您必须重载所有可能的赋值、运算符和内在函数。是的,这是很多工作。不,没有什么神奇的更快的方法可以在所有情况下导致自动转换。

module types
    use iso_fortran_env

    implicit none

    type MYTYPE_t
        real(real64) :: data
    contains
        procedure assign
        procedure add
        generic :: assignment(=) => assign
        generic :: operator(+) => add
    end type MYTYPE_t

    interface sqrt
      procedure sqrt_MTYPE
    end interface

contains

    subroutine assign(l,r)
      class(MYTYPE_t), intent(out) :: l
      real(real32), intent(in) :: r
      l%data = r
    end subroutine

    real(real64) function sqrt_MTYPE(x)
      type(MYTYPE_t), intent(in) :: x
      sqrt_MTYPE = sqrt(x%data)
    end function

    real(real64) function add(x, y)
      class(MYTYPE_t), intent(in) :: x
      integer, intent(in) :: y

      add = x%data + y
    end function
end module types

program test_program
    use types

    implicit none

    type(MYTYPE_T) :: test
    real(real64) :: foo

    ! This works
    test%data = 5.0
    ! Is there a way to be able things like this:
    test = 5.0
    print*, sqrt(test)

    foo = test + 3
end program

测试:

> gfortran override3.f90 
> ./a.out 
   2.2360679774997898 
于 2017-11-16T16:13:31.713 回答