Overloading a subroutine means to redefine its internal functionality for a customized behavior. Overall it adapts the class new characteristics to already wide-spread Fortran functionalities (==, =, + ,-, …).

Specifically, this post only focus on the operators (+,-,*,/).

In the following example, mynumber is generic class to hold any type of an integer number. For that reason, it seems interesting enough to be able to directly operate with its data.

The main program shows what is meant to do:

program numbers
  use mynumber_mod, only: mynumber

  implicit none

  type(mynumber) :: num1, num2, result
  num1 % value = 2
  num2 % value = 10

  num1 = num1 + 20     !< 2 + 20
  result = num1 + num2 !< 20 + 10
  result = 5 + result  !< 5 + 30

end program numbers

In short, mynumber type can directly operate with:

  • mynumber + mynumber
  • mynumber + scalar int
  • scalar int + mynumber

Therefore, there must be an implementation for each type of operation. Check below how to do it:

module mynumber_mod
  implicit none

  type mynumber
    integer :: value
  contains
   ! add
    procedure :: add_scalar_int
    procedure, pass(right) :: add_scalar_int_reverse
    procedure :: add_mynumber

    generic, public :: operator(+) => add_scalar_int, &
                   add_mynumber, add_scalar_int_reverse
  end type mynumber
contains

  ! add
  pure function add_mynumber(left, right) Result(total)
      class(mynumber), intent(in) :: left, right
      class(mynumber), allocatable :: total
      ...
      total % num = left % num + right % num
  end function add_mynumber


  pure function add_scalar_int_reverse(left, right) Result(total)
      integer, intent(in) :: left
      class(mynumber), intent(in) :: right
      class(mynumber), allocatable :: total
      ...
      total % num = left + right % num
  end function add_scalar_int_reverse


  pure function add_scalar_int(left, right) Result(total)
      class(mynumber), intent(in) :: left
      integer, intent(in) :: right
      class(mynumber), allocatable :: total
      ...
      total % num = left % num + right
  end function add_scalar_int

end module mynumber_mod

For each desired operation, it requires its own implementation. In order to include subtraction, division or multiplication, you only need to apply the same principle but with the following signs: -, *, /.

Leave a Reply

Your email address will not be published. Required fields are marked *