PeMa
PeMa

Reputation: 1696

Extending derived types in separate module without changing the type's name

I can extend a program by adding a module file in which I extend originally defined derived types like e.g.:

module mod1

   type type1
      real :: x
   end type

end module

module mod2       

   use mod1    
   type,extends(type1) :: type2
      contains
      procedure,pass :: g
   end type

contains

   function g(y,e)
      class(type2), intent(in) :: y
      real,intent(in) :: e 
      g=y%x+e
   end function

end module

program test

use mod2

type(type2) :: a

a%x=3e0
write(*,*) a%g(5e0)

end program

But with this solution I need to change the declaration of 'a' (type1->type2) in the calling program, each time when I'm adding another module. So my question is if there is a way around this, i.e. I can add a type bound procedure to a derived type in another module without changing the original name of the type.

I totally understand that this might not work since I could then declare a variable and extend its type later, what sounds problematic for me. So, I thought about the deferred statement. But this isn't really what I want, since I first have to ad it to the original definition and second I need to provide an interface and thus need to know about the variables of the later coming function (here g) already. However, maybe someone has a nice solution for this.

All this is of course to bring more structure in the program, especially when I think about different people working on one program at the same time, such a possibility to split workpackages seems rather useful.

Upvotes: 0

Views: 354

Answers (2)

To some extent submodules would help you, but they are implemented in the most widely used compilers. You could defer the implementation of the procedure to the submodule, but you would have to specify the interface anyway.

It isn't possible in any other way as far as I know.

Upvotes: 1

IanH
IanH

Reputation: 21431

You can rename entities that are use associated by using the renaming capability of the USE statement.

MODULE m2
  USE m1, chicken => type1
  TYPE, EXTENDS(chicken) :: type1
  ...

type1 in module m2 is a different type to type1 in module m1.

You could also do this renaming in the USE statement in your main program, or via some intermediate module.

If both type1 names are accessible in another scope and you reference the name type1, then your compiler will complain.

If you use this trick and other programmers read your code, then they might complain.

Upvotes: 1

Related Questions