I want to write a subroutine taking as argument two class objects which can be of any extended type from a common ancestor. Inside the subroutine I will have a type select to check the class. Since I know that the two objects will be of the same type, is it possible to avoid check the type of both? The following is a minimal example of what I would like to achieve (which at the moment is wrong):
program main
implicit none
type :: base
end type base
type, extends(base) :: ext1
integer :: i
end type ext1
type, extends(base) :: ext2
integer :: j
end type ext2
type(ext1) :: a, b
type(ext2) :: c, d
call my_subroutine(c, d)
contains
subroutine my_subroutine(obj1, obj2)
class(base), intent(in) :: obj1, obj2
select type(obj1)
type is (ext1)
print *, obj1%i + obj2%i
type is (ext2)
print *, obj1%j + obj2%j
end select
end subroutine my_subroutine
end program
I cannot access obj2%i
or obj2%j
since the type of obj2
has never been checked.
foo2.f08:29:40:
29 | print *, obj1%i + obj2%i
| 1
Error: ‘i’ at (1) is not a member of the ‘base’ structure
foo2.f08:31:40:
31 | print *, obj1%j + obj2%j
| 1
Error: ‘j’ at (1) is not a member of the ‘base’ structure
Is there a way to overcome this issue without explicitly checking the type of obj2
?