【问题标题】:Access Fortran custom type attributes by default默认访问 Fortran 自定义类型属性
【发布时间】:2018-04-29 20:55:00
【问题描述】:

现代 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

【问题讨论】:

  • 定义的分配是否满足您的要求?
  • 它以某种方式完成了这项工作。但问题是,必须覆盖所有默认运算符,并且它不适用于 fortran 内在函数。
  • 它会起作用的,看我的回答。

标签: fortran fortran2003 custom-type fortran2008


【解决方案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 

【讨论】:

  • 太棒了!我不知道像sqrt_MTYPE 这样的东西可以工作。谢谢
猜你喜欢
  • 1970-01-01
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-03
  • 1970-01-01
  • 1970-01-01
  • 2022-08-23
  • 2011-07-19
相关资源
最近更新 更多