一种Fortran函数/子例程,可返回实数、整数或字符串。
我想知道如何创建一个返回实数、整数或字符串的函数 例如,调用将是一种Fortran函数/子例程,可返回实数、整数或字符串。,fortran,derived-types,Fortran,Derived Types,我想知道如何创建一个返回实数、整数或字符串的函数 例如,调用将是write(*,*)dt%get(),其中get()将返回: 如果dt%isInteger=.true,则为整数。 如果dt%isReal=.true,则为实。 如果dt%isStr=.true,则为字符。 我相信,通过使用抽象接口使过程get()指向过程getInteger()、getReal()或getStr()可能实现这一点,但抽象接口定义需要定义输出类型,在我的例子中,它是变量 以下是相关代码: type :: dt
write(*,*)dt%get()
,其中get()
将返回:
- 如果
dt%isInteger=.true,则为整数。
- 如果
dt%isReal=.true,则为实。
- 如果
dt%isStr=.true,则为字符。
get()
指向过程getInteger()
、getReal()
或getStr()
可能实现这一点,但抽象接口定义需要定义输出类型,在我的例子中,它是变量
以下是相关代码:
type :: dt
real(dp) :: realValue
integer :: integerValue
character(*) :: strValue
logical :: isReal, isInteger, isStr
procedure(intf), pointer :: get
contains
procedure :: getReal, getInteger, getStr
end type
abstract interface
function intf(self)
import dt
class(dt) :: self
??? :: intf
end function
end interface
有什么想法吗?这在Fortran中根本不可能 您可以将泛型接口与不同的特定函数一起使用,但这些函数必须具有不同类型的参数(请参见几个内在函数,如
transfer()
如何使用mold
参数)。这称为TKR(类型、种类、等级)分辨率。无法根据参数值区分泛型函数
type :: dt
real(dp) :: realValue
integer :: integerValue
character(*) :: strValue !!!! <= THIS IS WRONG !!!!
logical :: isReal, isInteger, isStr
contains
generic :: get => getReal, getInteger, getStr
procedure :: getReal, getInteger, getStr
end type
function getReal(self, mold)
class(dt) :: self
real, intent(in) :: mold
end function
function getInteger(self, mold)
class(dt) :: self
integer, intent(in) :: mold
end function
function getString(self, mold)
class(dt) :: self
character(*), intent(in) :: mold
end function
还要注意不同长度的字符串。我在上面做了标记。您可能需要字符(:),可分配的
您还可以创建一个函数,该函数返回一个通用容器,然后从容器中提取值。甚至可以使用容器的重载赋值直接完成提取
您也可以只返回一个不受限制的多态变量(class(*)
)。您是否有一个简短的示例来说明class(*)
在这个上下文中的用法?好的,只有在您已经知道的情况下才能这样做。不幸的是,在主要的编译器中仍然存在编译器错误,所以我在准备一些东西时遇到了麻烦。包含class(*)
的容器会更好。
real_variable = object%get(1.0)
integer_variable = object%get(1)