Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Recognize data type automatically?

Zhanghong_T_
Novice
592 Views

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

0 Kudos
2 Replies
Jugoslav_Dujic
Valued Contributor II
592 Views
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:
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.


0 Kudos
Zhanghong_T_
Novice
592 Views

Oh, that's a good idea. Thank you very much!

Thanks,

Zhanghong Tang

0 Kudos
Reply