Search code examples
oopfortrangeneric-programming

Fortran OOP Generic


I am getting confused on the difference between using

Procedure :: momentum => particle_momentum 

and using

Procedure :: particle_momentum 
generic :: momentum => particle_momentum 

Here is a type declaration

type particle

  type(vector) :: position, velocity
  real :: mass

  contains

  procedure :: momentum => particle_momentum
  procedure :: energy => particle_energy

end type particle

Solution

  • Procedure :: momentum => particle_momentum

    defines a type-bound procedure, similar to virtual procedures in other languages. It is a binding of an existing procedure to perform the role of the type-bound procedure.

    They use the dynamic dispatch, i.e., when you call

      class(particle) :: o
      ..
      call o%momentum
    

    it is possible that if the dynamic type of o is en extended type (child) of particle you actually run a procedure that overrides particle_momentum. You don't know if you actually call the original, or the overriding procedure, until run-time.

    Now suppose you have

    procedure :: particle_momentum_int
    procedure :: particle_momentum_real
    generic :: momentum => particle_momentum_int, particle_momentum_real
    

    as

    subroutine particle_momentum_real(self, a)
       class(particle) :: self
       real :: a
    
    subroutine particle_momentum_int(self, a)
       class(particle) :: self
       integer :: a
    

    Then if you call

    class(particle) :: o !or just type(o)
    ..
    call o%momentum(1)
    

    you know that you call the _int variant by the rules of generic disambiguation and you know it at the compile-time. This is the static dispatch.