Reputation: 909
I want to implement a subroutine that can work with reals in single precision, double precision and extended precision. The only solution I can come up with is shown in the code below. This solution works but I have to duplicate the code 3 times. Can this code duplication be avoided?
module mymodule
....
! some code here
interface my_func
module procedure my_func_sp
module procedure my_func dp
module procedure my_func_ep
end interface
contains
subroutine my_func_sp(x,y)
real(kind=sp), dimension(:) :: x,y
... LONG IMPLEMENTATION HERE ...
end subroutine
subroutine my_func_dp(x,y)
real(kind=dp), dimension(:) :: x,y
... LONG IMPLEMENTATION HERE THAT IS EXACTLY THE SAME AS ABOVE ...
end subroutine
subroutine my_func_ep(x,y)
real(kind=ep), dimension(:) :: x,y
... LONG IMPLEMENTATION HERE THAT IS EXACTLY THE SAME AS THE TWO ABOVE ...
end subroutine
end module
Upvotes: 3
Views: 139
Reputation: 2605
If your entire code will use single, double, or quadruple precision reals, you can define a parameter real_kind in a module and use that parameter to specify kinds throughout your code, including the declarations of real variables in your subroutine. This solution does not work if your code calls more than one of my_func_sp, my_func_dp, and my_func_ep in a single run.
Upvotes: 0
Reputation: 78316
Can this code duplication be avoided? Not really, this is the way Fortran works. You could:
include
that file in each of the subroutines. Just take care that the included statements are valid for all kinds of the type. Take care too that the same statements work across kinds. If, for example, your included lines include comparisons with a tolerance, as many numeric codes do, you may have to take special care that the tolerance is adjusted wrt the kind.Upvotes: 6