1
votes

I try to construct a subroutine to reallocate memory for a type-independent allocatable array like this:

subroutine reallocate(vector, num)
implicit none
class(*), dimension(:), allocatable, intent(inout) :: vector
integer :: num

class(*), dimension(:), allocatable :: tmp
integer :: lb, ub, ii_

if (allocated(vector)) then
    ub = max(ubound(vector, 1), ub)
    lb = min(lbound(vector, 1), lb)

    if (ub .GT. ubound(vector, 1) .OR. lb .LT. lbound(vector, 1)) then
        allocate(tmp(ub:lb), source=vector)

        tmp(lbound(vector,1):ubound(vector,1)) = vector

        call move_alloc(tmp, vector)
    else
        return
    end if
else
    allocate(vector(num:num), source=vector)
    return
end if

return
end subroutine

For example, let's say I have a type(type1), allocatable :: v allocated within the indices -1 and 4, and I call reallocate(v, 6). After that I want v to be allocated between -1 and 6.

So, problem here comes when vector is already allocated, and I want to keep the information already stored in the vector by copying it to a newly reallocated temporal array (line that reads tmp(lbound(vector,1):ubound(vector,1)) = vector). gfortran complains: "Error: Nonallocatable variable must not be polymorphic in intrinsic assignment at (1) - check that there is a matching specific subroutine for '=' operator."

Is what I intent allowed in the Fortran 2003 standard? What would be the way to do this?

1
stackoverflow.com/q/27165854/577108 might be helpful to this question. - haraldkl

1 Answers

0
votes

There is no way to write such a type agnostic reallocation procedure in Fortran 2003, or Fortran 2008.

Your options are:

  • push the allocate statements that do the (re-)allocation, back up into the scope where the type is known, effectively repeating code for each reallocation;

  • explicitly rewrite the reallocation procedure for each type of interest; or

  • write the source code for the reallocation once generically, but then use INCLUDE tricks or similar to explicitly instantiate the procedure for each type of interest.

CLASS(*) is typically not appropriate as a generic programming facility. Even if it was possible to write the body of that procedure, it is impossible to usefully call.

(Note that the example code shown references undefined and potentially unallocated variables.)