Is there a way to have an argument for a subroutine have different types in different situations?
I have a simple subroutine that reads a line from a csv file and puts the value after the comma into a variable. (It does a few other things, hence making it a subroutine, but those things do not affect what I'm trying to do). Sometimes, that variable is a integer, and sometimes it is a real. Is there a way to allow the variable type to be dynamically chosen? Or set outside of the subroutine?
Obviously, I could create two different versions of my subroutine, one for ints and one for reals, but I'd like to avoid that.
I am using Intel Visual Fortran.
program myProgram
implicit none
integer :: fileID, variableINT
real :: variableREAL
open(fileID,'SomeFile.csv')
call readerSub(fileID, variableINT)
call readerSub(fileID, variableREAL)
close(fileID)
end program
subroutine readerSub(fID, outvar)
integer, intent(in) :: fID
XXXXXXX, intent(out) :: outvar
character(100) :: line
integer :: com_pos
read(fID, "(A)")line
com_pos = index(line, ",")
read(line(pos+1:),*)outvar
end subroutine
Updated with francescalus' suggestion of polymorphism. Seems to work pretty well!
subroutine readerSub(fID, outvar)
integer, intent(in) :: fID
class(*),intent(out) :: outvar
character(100) :: line
integer :: com_pos
read(fID, "(A)")line
com_pos = index(line, ",")
select type(outvar)
type is(integer)
read(line(pos+1:),*)outvar
type is(real)
read(line(pos+1:),*)outvar
end select
end subroutine