- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Hello all,
I have a subroutine which is the same for both real and complex input data, for example, as follows:
subroutine printabs(a)
! define a
print *,abs(a)
end subroutine
My question is: how to define the input variable a to let it be called in the following drive program?
implicit none
real*8::a
complex*16::b
call printabs(a)
call printabs(b)
end
Thanks,
Zhanghong Tang
Link Copied
2 Replies
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
In essence, you can't. All data types must be known at compile time, and Fortran doesn't have a feature like C++ templates (which represent a notational shortcut, where the compiler "figures out" the required datatype from given template code).
A common trick to workaround that is to play with INCLUDE files. In essence, if you have code blocks which are identical for different datatypes (such as your print*, abs(a)), you can move them to a separate files. Still, you have to "instantiate" subroutine headers for each type manually.
Using that technique (plus some generic routines), your code above would translate to:
A common trick to workaround that is to play with INCLUDE files. In essence, if you have code blocks which are identical for different datatypes (such as your print*, abs(a)), you can move them to a separate files. Still, you have to "instantiate" subroutine headers for each type manually.
Using that technique (plus some generic routines), your code above would translate to:
File Code.fd:
print* abs(a)
File MyMod.f90
MODULE MyMod
INTERFACE printabs
MODULE PROCEDURE printabs_r8
MODULE PROCEDURE printabs_c16
!repeat for each datatype
END INTERFACE
CONTAINS
SUBROUTINE printabs_r8(a)
REAL(8):: a
INCLUDE "Code.fd"
END SUBROUTINE printabs_r8(a)
SUBROUTINE printabs_c16(a)
COMPLEX(8):: a
INCLUDE "Code.fd"
END SUBROUTINE printabs_c16(a)
...
END MODULE MyMod
And your program will look the same as you posted (plus USE MyMod). Of course, for one-line Code.fd, it's more hussle than it's worth, but the technique is common for operations such as sorting and linear equation systems, where Code.fd is non-trivial.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Oh, that's a good idea. Thank you very much!
Thanks,
Zhanghong Tang
Reply
Topic Options
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page