These are chat archives for Fortran-FOSS-Programmers/General-Discussion

13th
Jun 2016
Stefano Zaghi
@szaghi
Jun 13 2016 14:18

Help Wanted for polymorphic arguments!

My dear, I have a trivial question to which I am not able to respond... I need your help

Let us suppose we an subroutine that among others accept 3 unlimited polymorphic dummies

subroutine foo(arg1, arg2, arg3, ...)
class(*), intent(in) :: arg1
class(*), intent(in) :: arg2
class(*), intent(in) :: arg3
...
end subroutine foo

Before using the arg# I have to check their type/class, right? so something like

subroutine foo(arg1, arg2, arg3, ...)
class(*), intent(in) :: arg1
class(*), intent(in) :: arg2
class(*), intent(in) :: arg3
...
select type(arg1)
type is(integer)
    select type(arg2)
    type is(integer)
      select type(arg3)
      type is(integer)
           ! do my integer stuff
      end select
    end select
end select
end subroutine foo

That is very verbose and error-prone. In the case I am sure that the combination of arg# is always uniform, namely they are ALL integers, reals, complexs... and I never fall into the case that one is real and others are integers, two are reals and the last is integer and similar etherogeneous cases, there is something smarter that I can do? I am confident that there is no other way to deal with unlimited polymorphic other than select type, but I prefer to listen this from your voice :smile:

Thank you far any comments!

Tom Dunn
@tomedunn
Jun 13 2016 15:10
I think I would just write a separate subroutine for each type of argument and then overload a generic subroutine to call them all via the same subroutine. It doesn't allow you to reuse the code between the subroutines but it does allow you to get rid of the nested select type statements.
Stefano Zaghi
@szaghi
Jun 13 2016 15:19
Hi @tomedunn thank you for your help. Yes, generic name and dynamic dispatch was my first approach, but then I come to unlimited polymorphic just to avoi to write tons of foo_real_64, foo_real_32, foo_integer_32... where only few statements differ (again error-prone). Indeed I have written a pre-processor just for this case, but I have write a piece of code with a minimum dependency for easy-sharing and adding a pre-processor dependency is not a viable approach. Anyhow thank you very much!