用Fortran重载函数 [英] Overloading functions with Fortran
问题描述
接口检查
模块过程check_int,check_real
结束接口
包含
子程序check_int(cur,dname,func_name,fname)
整数,可分配,intent(in) :: cur(:)
字符(*):: dname,func_name,fname
...
结束子程序
子程序check_real(cur,dname,func_name ,fname)
real,allocatable,intent(in):: cur(:)
字符(*):: dname,func_name,fname
...
结束子程序
所以,这样做不好吗?
编辑:用关键字调用函数不会改变任何东西。 你的例子是完全有效。它们可以通过参数的类型进行区分。那么名字并不重要。在你的情况下, cur
参数的类型不同。
具有相同名称的参数可以通过它们类型,种类或等级(TKR兼容性)。
引用文章的要点是,您无法仅通过参数的ORDER区分两个特定的过程。这是因为可以按任意顺序使用关键字参数调用这些过程。这可以通过为参数使用不同的名称来克服。
否则,为具有相同名称参数的通用程序声明更具体的过程,但具有不同的类型/种类/等级是非常普遍的,也是完全有效的。
Fortran 2003/2008增加了一些泛型解析的可能性。也可以通过它们的参数的pointer / allocatable属性和过程指针伪参数来区分过程。
In Fortran 90, we can overload functions with an interface. However, according to this site, we cannot define these functions with the same arguments name. With gfortran, it does not seem to be a problem as the following code works well enough:
interface check
module procedure check_int, check_real
end interface
contains
subroutine check_int(cur, dname, func_name, fname)
integer, allocatable, intent(in) :: cur(:)
character(*) :: dname, func_name, fname
...
end subroutine
subroutine check_real(cur, dname, func_name, fname)
real, allocatable, intent(in) :: cur(:)
character(*) :: dname, func_name, fname
...
end subroutine
So, is it bad practice to do so?
Edit: Calling the function with keywords does not change anything.
Your example is perfectly valid. They can be distinguished by the TYPE of the arguments. The names are not important then. In your case the type of the cur
argument differs.
The arguments with the same name can be distinguished by their type, kind or rank (TKR compatibility).
The point of the referenced article is that you cannot distinguished two specific procedures only by the ORDER of the arguments. It is because the procedures can be called with the keyword arguments in any order. This can be overcomed by using different names for the arguments.
Otherwise declaring more specific procedures for a generic one with the same names of arguments, but with different types/kinds/ranks is very common and perfectly valid.
Fortran 2003/2008 adds some more possibilities to generic resolution. It is also possible to distinguish procedures by the pointer/allocatable attribute of their arguments and by the procedure pointer dummy arguments.
这篇关于用Fortran重载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!