2014-05-17 23 views
3

我有一個模塊,它定義了三種類型和一些操作。Fortran中的模板?

在一個單獨的模塊中,我想定義一個算法,使用模塊中定義的操作對這些類型中的任何一個進行操作。算法是相同的,無論類型如何。我可以重載它,但是我想知道是否可以通過定義某種模板算法來節省大量輸入。我想到的是類似C++中的類模板。

感謝

回答

3

Fortran語言沒有模板,但你可以把常見的包含文件處理不同類型的雜牌組裝電腦來模擬模板,該函數的代碼如以下代碼所示:

! 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。

您可能會感興趣。我沒有嘗試過。

+0

爲方便起見,引用的論文是[doi:10.1145/1753166.1753167](http://dx.doi.org/10.1145/1753166.1753167)。 – francescalus