在 Fortran 中确定变量类型 [英] Determining variable type in Fortran

查看:32
本文介绍了在 Fortran 中确定变量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Fortran 中,有没有办法确定变量的类型?

In Fortran, is there a way to determine the type of a variable?

需要变量类型的可能用例如下.我们将变量的类型作为参数传递给函数,以便能够使用该函数调用特定于类型的代码,从而无需为每种数据类型使用单独的类似函数.

A possible use case where the type of a variable would be needed is the following. We pass a variable's type as an argument to a function, to be able to call type-specific code with that function, thus eliminating the need to have separate similar functions for each data type.

推荐答案

如果你弄乱了 KIND 内在函数和指针,你也许可以做你想做的事,但如果你只关心函数的签名和子例程,留给 Fortran.如果你定义

Well you might be able to do what you want if you mess about with the KIND intrinsic and POINTERs, but if you are only concerned with the signature of functions and subroutines, leave it to Fortran. If you define

function calc8(arg1)
    real(8), intent(in) :: arg1
    ...

function calc4(arg1)
    real(4), intent(in) :: arg1
    ...

在一个模块中,并声明一个这样的接口

in a module, and declare an interface like this

interface calc
    module procedure calc8
    module procedure calc4
end interface

(警告,我没有仔细检查语法,这是你的责任.)

(Warning, I haven't checked the syntax in detail, that's your responsibility.)

然后 Fortran 会将调用匹配到正确版本的函数.当然,您必须编写函数的两个版本,但这确实是 Fortran 95 的做法.这可能很乏味,我倾向于编写一个通用版本并运行一个 sed 脚本来专门化它.这有点杂乱无章,但确实有效.

then Fortran will match the call to the right version of the function. Sure, you have to write both versions of the function, but that's really the Fortran 95 way of doing it. This can be quite tedious, I tend to write a generic version and run a sed script to specialise it. It's a bit of a kludge but it works.

如果函数的代码除了参数的种类之外是相同的,我有时会为 real(8)(或其他)编写函数并为 real(4) 编写一个版本,它调用 real(8) 包装的版本在类型转换中.

If the code of the function is identical apart from the kind of the arguments I sometimes write the function for real(8) (or whatever) and write a version for real(4) which calls the real(8) version wrapped in type conversions.

在 Fortran 2003 中,改进了定义多态和泛型函数的方法,但我还没有真正理解它们.

In Fortran 2003 there are improved ways of defining polymorphic and generic functions, but I haven't really got my head around them yet.

这篇关于在 Fortran 中确定变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆