Reputation: 1525
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
Upvotes: 2
Views: 192
Reputation: 4129
Simply saying, "generic" is to make life easier, the compiler chooses the suitable form of a procedure among others just by calling a specific command, for example, you want to call the right constructor of an object with "initialize" command. There are some rules should be obeyed the compiler can distinguish them.
On the other hand, "procedure:: x=>y" is employed to override/point one of object procedures (x) to a new function (y).
Upvotes: 0
Reputation: 59998
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.
Upvotes: 3