Problem background
Suppose I need to develop a multi-precision math library and define a polymorphic function eye
.
Is there any magic in Fortran to make x=eye(2,2)
return the value of the eye
function according to the type of x
?
Change to subroutine?
subroutines
have different advantages from functions
. Functions can be written in formulas.
Overload equal sign(assignment(=)
)?
Fortran Class (*) in Function Result
module hello_bob
interface assignment(=)
module procedure int_equal_func_class
end interface
contains
subroutine int_equal_func_class(a,b)
integer, intent(out) :: a(:)
class(*), intent(in) :: b(:)
select type (b)
type is (integer)
a = b
end select
end subroutine int_equal_func_class
function func(a)
class(*), intent(in) :: a(:)
class(*), allocatable :: func(:)
! No intrinsic assignment supported, also see note about bounds
allocate(func, source=a)
end function func
end module hello_bob
program bob
use hello_bob
integer i(4)
i=func([1,2,3,4])
print*, i
end program bob
Is there any downside to customizing such overloads?
For example, print *, eye(2,2)
will be invalid?
Or does Fortran have other magic?
(I’m just interested, and I don’t really need a solution. Thank you! )