Operator overloading
| Interface operator | |
| Interface assignment | |
| Define + for a type | |
| Overload sparingly |
Interface operator
An interface operator block tells the compiler that a familiar symbol such as plus also accepts a user type.
Inside the block, name the module procedures that implement the operation for each combination of argument types.
The block below connects the plus sign with a function that adds two points.
interface operator(+)
module procedure point_add
end interface
Interface assignment
An interface assignment block extends the equals sign so that assignment between user types can run custom logic.
The implementing subroutine takes two arguments: the left side with intent out or inout, and the right side with intent in.
This block registers a copy routine for the point type.
interface assignment(=)
module procedure point_copy
end interface
Define + for a type
The implementing function takes two values with intent in and returns the combined value through the result clause.
Keep the meaning close to the built-in operator: plus should add, not multiply or print, so readers are never surprised.
This module adds points component by component and exposes the operator to client code.
module point_ops
implicit none
type :: point
real :: x
real :: y
end type point
interface operator(+)
module procedure point_add
end interface
contains
function point_add(a, b) result(c)
type(point), intent(in) :: a, b
type(point) :: c
c%x = a%x + b%x
c%y = a%y + b%y
end function point_add
end module point_ops
Overload sparingly
Overloading makes code read well only when the new meaning matches the old one, so limit it to natural cases like math vectors.
Avoid clever symbols for unrelated actions, and never change the number of operands or the precedence of an operator.
When the operation has no clear symbol, a named function or type-bound procedure communicates the idea better than an overload.
program demo
implicit none
use point_ops
type(point) :: a, b, c
a = point(1.0, 2.0)
b = point(3.0, 4.0)
c = a + b
print *, c
end program demo
Next: Finalization
Article author: Arthur Isaev