现代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
答案 0 :(得分: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