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

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

问题描述

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

一个可能的用例需要变量的类型如下。我们将一个变量的类型作为参数传递给一个函数,以便能够使用该函数调用特定于类型的代码,从而消除了为每个数据类型分别使用相似的函数的必要。

解决方案

好吧,如果你想知道KIND内部函数和POINTER,你可能可以做你想做的事情,但是如果你只关心函数和子程序的签名,它到Fortran。如果你定义

 函数calc8(arg1)
real(8),intent(in):: arg1
...



<$ p
$ arg1

$ arg1
真实(4),intent(in):: arg1
$ pre

在一个模块中,并且声明一个类似于这样的接口

 接口calc 
模块过程calc8
模块过程calc4
结束接口

(警告,我没有详细检查语法,这是您的责任。)

然后,Fortran将匹配该函数的正确版本。当然,您必须编写这两个版本的函数,但这确实是Fortran 95的做法。这可能非常乏味,我倾向于编写一个通用版本并运行sed脚本来专门化它。这是一个kludge,但它的工作原理。



如果函数的代码与参数的类型相同,我有时会为真实(8) (或其他),并为真实(4)编写一个版本,该版本调用包装在类型转换中的实数(8)版本。



在Fortran 2003中,多态和泛型函数,但是我还没有真正了解他们。


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.

解决方案

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
    ...

and

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.)

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.

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.

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天全站免登陆