使用Iso_Fortran_Env设置函数的Kind值 [英] Using Iso_Fortran_Env to set a function's Kind value

查看:431
本文介绍了使用Iso_Fortran_Env设置函数的Kind值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用ISO Fortran Env的内在函数以一种Fortran 2008惯用的方式设置函数的返回KIND值?

How would one go about using ISO Fortran Env's intrinsic to set a function's return KIND value in a manner which is idiomatic to Fortran 2008?

通常在主程序中,我可以按如下方式使用ISO Fortran内在函数:

Normally within the main program, I can just use the ISO Fortran intrinsics as follows:

program name here
    use iso_fortran_env
    implicit none
    integer, parameter :: double=REAL64
    real(kind=double) :: some_variable
end program name here

但是似乎没有一种方便的方法将这些内在函数用于外部函数,因为REAL64和double都只能在上面的主函数中定义.尝试在main中定义函数的KIND,如下所示:

But there doesn't seem to be a convenient way to use these intrinsics for external functions, since REAL64 and double would both be defined only within the main function above. Attempting to define the function's KIND within main as follows:

program name here
    use iso_fortran_env
    implicit none
    integer, parameter :: double=REAL64
    real(kind=double) :: some_function
    ! Do stuff
end program name here
real function some_function()
    ! Do stuff
end some_function

至少在我的系统上,抛出类型不匹配错误(在我的系统上,double被定义为KIND = 8,默认实数被定义为KIND = 4).我总是可以只使用real(kind=8) function some_function(),但是我不想出于便携性考虑.另外,在一个地方使用iso_fortran_env中的REAL64,而在另一地方使用KIND = 8只是感觉很脏.

At least on my system, throws a type mismatch error (double gets defined as KIND=8, and a default real gets defined as a KIND=4 on my system). I could always just use real(kind=8) function some_function(), but I'd prefer not to in the interest of portability. Plus, it just feels dirty to use REAL64 from iso_fortran_env in one place, only to turn around and use KIND=8 in another place.

是否有一种简单的(或至少是可读的)方式来实现这一目标,例如下面?

Is there an easy (or at least, readable) way to accomplish that, such as below?

real(kind=REAL64) function some_function()

推荐答案

您提出的问题提供了一个解决方案,并且该解决方案效果很好.正如IanH指出的那样,标准措词有些含糊,但我读这句话的意思是允许这样做,并且编译器确实接受这种语法:

You start your question offers a solution at the and that solutions works well. As IanH points out there is some ambiguity in the standard wording, but I read it as saying it is allowed and compilers do accept this syntax:

fundef.f90:

fundef.f90:

real(kind=REAL64) function some_function()
  use iso_fortran_env
  some_function = 1._real64
end

编译:

> gfortran -c funkind.f90 
> 

您可以使用在函数内部使用的模块中定义的种类.还通过Intel Fortran和Oracle Studio进行了测试.

You can use the kind defined in a module used inside the function. Tested also with Intel Fortran and Oracle Studio.

在现代Fortran中,所有功能无论如何都应该在模块中定义,但是如果您希望从仅在函数内部使用的模块中获取某种功能,则可能在这里.

In modern Fortran all functions should be defined in a module anyway, but if you wish to you a kind from a module used only inside the function, the possibility is here.

这篇关于使用Iso_Fortran_Env设置函数的Kind值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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