Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28701 Discussions

Overring intrinsic procedures with type bound procedures

Andrew_Smith
Valued Contributor I
504 Views
In F2003 (not yet IVF) there is overiding for operators and assignment using type bound procedures but how about intrinsics?

When we have a type bound precedure we must call using % notation as below. But this will mean we do not overide the intrinsic. Or am I wrong?

MODULE x

TYPE y
REAL z
CONTAINS
PROCEDURE abs => ABS_a
END TYPE

CONTAINS

CLASS(y) FUNCTION ABS_a(me)
CLASS(y), INTENT(IN) :: me
ABS_a%z = ABS(me.z)
END FUNCTION

END MODULE

PROGRAM TEST
TYPE(y) a, b
a%z = -1.0
b = abs(a) !Illegal use of intrinsic abs
b = a%abs !Will use type bound procedure
END PROGRAM
0 Kudos
4 Replies
IanH
Honored Contributor III
504 Views
I believe you are right. To actually "override" the intrinsic you would need to provide the usual generic interface. The specific procedure would be selected on the basis of the declared type of the argument. This specific procedure could then forward the call to the appropriate type bound procedure.

[fortran]MODULE x
  TYPE y
    REAL z
  CONTAINS
    PROCEDURE :: abs => ABS_a
  END TYPE

  ! So the intrinsic behaves like we'd expect.
  INTERFACE Abs
    PROCEDURE abs_forwarder
  END INTERFACE Abs
CONTAINS
  ! gets called when dynamic type of me is a y
  FUNCTION ABS_a(me) RESULT
    CLASS(y), INTENT(IN) :: me
    CLASS(y), ALLOCATABLE :: r
    !****
    ALLOCATE(y:: r)
    r%z = ABS(me%z)
  END FUNCTION

  ! gets called when declared type of me is a y
  FUNCTION abs_forwarder(me) RESULT
    CLASS(y), INTENT(IN) :: me
    CLASS(y), ALLOCATABLE :: r
    !****
    ! polymorphic call to abs, which might go to ABS_a or equivalent override 
    ! in an extension of y.  F2008 allows assignment here?
    ALLOCATE(r, SOURCE=me%abs)
  END FUNCTION abs_forwarder
END MODULE x    
    [/fortran]
But don't be surprised if I'm totally wrong :).
0 Kudos
Arjen_Markus
Honored Contributor I
504 Views
Why the allocate statements? Isn't the variable r that holds the function value already allocated?

Regards,

Arjen
0 Kudos
asymptotic
Beginner
504 Views

module module_x

implicit none

type, public:: y

real:: z

contains

procedure, pass:: abs => abs_a

end type

contains

type(y) function abs_a(me)

implicit none

class(y), intent(in) :: me

abs_a % z = abs(me % z)

return

end function

end module

program test

use module_x

implicit none

type(y):: a, b

a % z = -1.0

b = abs_a(a)

b = a % abs() ! type bound procedure

stop

end program

0 Kudos
Andrew_Smith
Valued Contributor I
504 Views
It seams to me that it would have made sence if F2003 or F2008 said that intrinsic procedures should be callable as type bound procedures too, then we could all adopt the new % notation for calling stuff.
0 Kudos
Reply