Fortran 中的模板? [英] Template in Fortran?

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

问题描述

我有一个模块,它定义了三种类型以及对它们的一些操作.

I have a module that defines three types and and some operations on them.

在一个单独的模块中,我想定义一个算法,该算法使用模块中定义的操作对这些类型中的任何一种进行操作.无论类型如何,算法都是相同的.我可以重载它,但我想知道是否可以通过定义某种模板算法来节省大量输入.我想到的是类似于 C++ 中的类模板.

In a separate module, I want to define an algorithm that operates on either one of these types using the operations defined in the module. The algorithm is the same, regardless of the type. I can overload it, but I was wondering if I can save a lot of typing by defining some sort of template algorithm. What I have in mind is something like class templates in C++.

谢谢

推荐答案

Fortran 没有模板,但是你可以将处理不同类型的函数的通用代码放在一个包含文件中作为一个 kludge 来模拟模板,如下所示这段代码:

Fortran does not have templates, but you can put the code common to the functions handling different types in an include file as a kludge to simulate templates, as shown in this code:

! file "cumul.inc"
! function cumul(xx) result(yy)
! return in yy(:) the cumulative sum of xx(:)
! type, intent(in) :: xx(:)
! type             :: yy(size(xx))
integer :: i,n
yy = 0
n  = size(xx)
if (n < 1) return
yy(1) = xx(1)
do i=2,n
   yy(i) = yy(i-1) + xx(i)
end do
return
! end function cumul
! end file "cumul.inc"

module foo
implicit none
integer, parameter :: sp = kind(1.0), dp = kind(1.0d0)
interface cumul
   module procedure cumul_double,cumul_real,cumul_int
end interface cumul
contains
!
function cumul_double(xx) result(yy)
real(kind=dp), intent(in) :: xx(:)
real(kind=dp)             :: yy(size(xx))
include "cumul.inc"
end function cumul_double
!
function cumul_real(xx) result(yy)
real(kind=sp), intent(in) :: xx(:)
real(kind=sp)             :: yy(size(xx))
include "cumul.inc"
end function cumul_real
!
function cumul_int(xx) result(yy)
integer, intent(in) :: xx(:)
integer             :: yy(size(xx))
include "cumul.inc"
end function cumul_int
end module foo

program xcumul
use foo, only: cumul
print*,cumul([10,20,30])
print*,cumul(sin([10.0,20.0,30.0]))
print*,cumul(sin([10.0d0,20.0d0,30.0d0]))
end program xcumul
! output:
! 10 30 60
! -0.5440211 0.36892414 -0.6191075
! -0.5440211108893698 0.3689241398382579 -0.6191074842546039

论文中提到的工具

Car、David 和 Michael List(2010 年).PyF95++:Fortran 95/2003 语言的模板功能.ACM Fortran 论坛 29(1), 2-20.

Car, David and Michael List (2010). PyF95++: A Templating Capability for the Fortran 95/2003 Language. ACM Fortran Forum 29(1), 2-20.

您可能会感兴趣.我没试过.

may interest you. I have not tried it.

这篇关于Fortran 中的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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