Is it possible in Fortran to determine if two polymorphic objects are the same derived type?

126 Views Asked by At

Is it possible to take two polymorphic objects and determine if they are of the same derived type (or class)? The intention is to use it as a clean way to filter a generic linked list.

Something like the following mock code.

function isSameType(a, b) result(itIs)

    !arguments
    class(*), intent(in) :: a
    class(*), intent(in) :: b

    !output
    logical :: itIs

    !return true if a and b are both the same type
    !return false if a and b are not

end function isSameType
1

There are 1 best solutions below

0
francescalus On BEST ANSWER

The standard inquiry function same_type_as tests equality of dynamic type of two objects:

program typetest
  implicit none

  type t1
  end type t1

  type t2
  end type t2

  class(*), allocatable :: a, b

  allocate(t1 :: a)
  allocate(t2 :: b)

  print *, SAME_TYPE_AS(a,b)   ! False
end program

same_type_as does not test declared type (except where this is the same thing). It does not consider kind parameters:

program partest
  implicit none

  type :: t1(n)
     integer, kind :: n
  end type t1

  type(t1(1)) :: a
  type(t1(2)) :: b

  print *, SAME_TYPE_AS(a,b)   ! True
end program

Further, to get a useful result you'll be wanting (at least) one of a and b to be of extensible dynamic type. While you can ask

program intrinsictest

  implicit none

  class(*), allocatable :: a, b

  allocate(real :: a)
  allocate(double precision :: b)

  print *, SAME_TYPE_AS(a,b)  ! ...
end program

the result is processor dependent (could be true or false).