最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

可以返回实数、整数或字符串的 Fortran 函数子例程.

SEO心得admin39浏览0评论
本文介绍了可以返回实数、整数或字符串的 Fortran 函数/子例程.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道如何创建一个返回实数、整数或字符串的函数.

I would like to know how to create a function that either returns a real, an integer or a string.

例如,调用将是 write(*,*)dt%get() 其中 get() 将返回:

For example, the call would be write(*,*)dt%get() where get() would return :

  • 如果 dt%isInteger = .true,则为整数.
  • 如果 dt%isReal = .true.
  • 则为实数
  • 一个字符,如果 dt%isStr = .true.

我相信这可能通过使用抽象接口使过程 get() 指向过程 getInteger()、getReal() 或 getStr() 但抽象接口定义需要定义输出类型,在我的例子中,它是变量.

I believe this might be possible by using an abstract interface to make procedure get() point to either procedure getInteger(), getReal() or getStr() but the abstract interface definition needs to define the ouput type which is, in my case, variable.

相关代码如下:

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 中根本不可能.

That is simply impossible in Fortran.

您可以使用具有不同特定函数的通用接口,但这些函数必须具有不同类型的参数(请参阅几个内部函数,例如 transfer() 如何使用 mold 论点).这称为 TKR(类型、种类、等级)解析.泛型函数不能根据参数的值来区分.

You can use a generic interface with different specific functions, but these functions must have arguments of different types (see how several intrinsic functions, like transfer() use a mold argument). This is called the TKR (type, kind, rank) resolution. Generic functions cannot be distinguished based on a value of an argument.

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

如您所见,在调用 get() 时,您必须知道正确的类型.你这样称呼它

As you see, you have to know the correct type when calling get(). You call it like

real_variable = object%get(1.0) integer_variable = object%get(1)

还要注意不同长度的字符串.我在上面做了标记.你可能想要character(:), allocatable.

Be also careful about strings of different lengths. I marked it above. You probably want character(:), allocatable.

您还可以创建返回通用容器的函数,然后从容器中提取值.提取甚至可以直接使用容器的重载赋值来完成.

You can make also function which returns a generic container and then extract the value from the container. The extraction could even be done directly using an overloaded assignment for the container.

你也可以只返回一个无限的多态变量(class(*)).

You could also just return an unlimited polymorphic variable (class(*)).

发布评论

评论列表(0)

  1. 暂无评论